babylon.max.js 4.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985
  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. var BABYLON;
  29. (function (BABYLON) {
  30. /**
  31. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  32. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  33. */
  34. var EffectFallbacks = /** @class */ (function () {
  35. function EffectFallbacks() {
  36. this._defines = {};
  37. this._currentRank = 32;
  38. this._maxRank = -1;
  39. }
  40. /**
  41. * Removes the fallback from the bound mesh.
  42. */
  43. EffectFallbacks.prototype.unBindMesh = function () {
  44. this._mesh = null;
  45. };
  46. /**
  47. * Adds a fallback on the specified property.
  48. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  49. * @param define The name of the define in the shader
  50. */
  51. EffectFallbacks.prototype.addFallback = function (rank, define) {
  52. if (!this._defines[rank]) {
  53. if (rank < this._currentRank) {
  54. this._currentRank = rank;
  55. }
  56. if (rank > this._maxRank) {
  57. this._maxRank = rank;
  58. }
  59. this._defines[rank] = new Array();
  60. }
  61. this._defines[rank].push(define);
  62. };
  63. /**
  64. * Sets the mesh to use CPU skinning when needing to fallback.
  65. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  66. * @param mesh The mesh to use the fallbacks.
  67. */
  68. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  69. this._mesh = mesh;
  70. if (rank < this._currentRank) {
  71. this._currentRank = rank;
  72. }
  73. if (rank > this._maxRank) {
  74. this._maxRank = rank;
  75. }
  76. };
  77. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  78. /**
  79. * Checks to see if more fallbacks are still availible.
  80. */
  81. get: function () {
  82. return this._currentRank <= this._maxRank;
  83. },
  84. enumerable: true,
  85. configurable: true
  86. });
  87. /**
  88. * Removes the defines that shoould be removed when falling back.
  89. * @param currentDefines defines the current define statements for the shader.
  90. * @param effect defines the current effect we try to compile
  91. * @returns The resulting defines with defines of the current rank removed.
  92. */
  93. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  94. // First we try to switch to CPU skinning
  95. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  96. this._mesh.computeBonesUsingShaders = false;
  97. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  98. var scene = this._mesh.getScene();
  99. for (var index = 0; index < scene.meshes.length; index++) {
  100. var otherMesh = scene.meshes[index];
  101. if (!otherMesh.material) {
  102. continue;
  103. }
  104. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  105. continue;
  106. }
  107. if (otherMesh.material.getEffect() === effect) {
  108. otherMesh.computeBonesUsingShaders = false;
  109. }
  110. else {
  111. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  112. var subMesh = _a[_i];
  113. var subMeshEffect = subMesh.effect;
  114. if (subMeshEffect === effect) {
  115. otherMesh.computeBonesUsingShaders = false;
  116. break;
  117. }
  118. }
  119. }
  120. }
  121. }
  122. else {
  123. var currentFallbacks = this._defines[this._currentRank];
  124. if (currentFallbacks) {
  125. for (var index = 0; index < currentFallbacks.length; index++) {
  126. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  127. }
  128. }
  129. this._currentRank++;
  130. }
  131. return currentDefines;
  132. };
  133. return EffectFallbacks;
  134. }());
  135. BABYLON.EffectFallbacks = EffectFallbacks;
  136. /**
  137. * Options to be used when creating an effect.
  138. */
  139. var EffectCreationOptions = /** @class */ (function () {
  140. function EffectCreationOptions() {
  141. }
  142. return EffectCreationOptions;
  143. }());
  144. BABYLON.EffectCreationOptions = EffectCreationOptions;
  145. /**
  146. * Effect containing vertex and fragment shader that can be executed on an object.
  147. */
  148. var Effect = /** @class */ (function () {
  149. /**
  150. * Instantiates an effect.
  151. * An effect can be used to create/manage/execute vertex and fragment shaders.
  152. * @param baseName Name of the effect.
  153. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  154. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  155. * @param samplers List of sampler variables that will be passed to the shader.
  156. * @param engine Engine to be used to render the effect
  157. * @param defines Define statements to be added to the shader.
  158. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  159. * @param onCompiled Callback that will be called when the shader is compiled.
  160. * @param onError Callback that will be called if an error occurs during shader compilation.
  161. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  162. */
  163. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  164. if (samplers === void 0) { samplers = null; }
  165. if (defines === void 0) { defines = null; }
  166. if (fallbacks === void 0) { fallbacks = null; }
  167. if (onCompiled === void 0) { onCompiled = null; }
  168. if (onError === void 0) { onError = null; }
  169. var _this = this;
  170. /**
  171. * Unique ID of the effect.
  172. */
  173. this.uniqueId = 0;
  174. /**
  175. * Observable that will be called when the shader is compiled.
  176. */
  177. this.onCompileObservable = new BABYLON.Observable();
  178. /**
  179. * Observable that will be called if an error occurs during shader compilation.
  180. */
  181. this.onErrorObservable = new BABYLON.Observable();
  182. /**
  183. * Observable that will be called when effect is bound.
  184. */
  185. this.onBindObservable = new BABYLON.Observable();
  186. this._uniformBuffersNames = {};
  187. this._isReady = false;
  188. this._compilationError = "";
  189. this.name = baseName;
  190. if (attributesNamesOrOptions.attributes) {
  191. var options = attributesNamesOrOptions;
  192. this._engine = uniformsNamesOrEngine;
  193. this._attributesNames = options.attributes;
  194. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  195. this._samplers = options.samplers;
  196. this.defines = options.defines;
  197. this.onError = options.onError;
  198. this.onCompiled = options.onCompiled;
  199. this._fallbacks = options.fallbacks;
  200. this._indexParameters = options.indexParameters;
  201. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  202. if (options.uniformBuffersNames) {
  203. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  204. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  205. }
  206. }
  207. }
  208. else {
  209. this._engine = engine;
  210. this.defines = defines;
  211. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  212. this._samplers = samplers;
  213. this._attributesNames = attributesNamesOrOptions;
  214. this.onError = onError;
  215. this.onCompiled = onCompiled;
  216. this._indexParameters = indexParameters;
  217. this._fallbacks = fallbacks;
  218. }
  219. this.uniqueId = Effect._uniqueIdSeed++;
  220. if (this._getFromCache(baseName)) {
  221. this._prepareEffect();
  222. return;
  223. }
  224. var vertexSource;
  225. var fragmentSource;
  226. if (baseName.vertexElement) {
  227. vertexSource = document.getElementById(baseName.vertexElement);
  228. if (!vertexSource) {
  229. vertexSource = baseName.vertexElement;
  230. }
  231. }
  232. else {
  233. vertexSource = baseName.vertex || baseName;
  234. }
  235. if (baseName.fragmentElement) {
  236. fragmentSource = document.getElementById(baseName.fragmentElement);
  237. if (!fragmentSource) {
  238. fragmentSource = baseName.fragmentElement;
  239. }
  240. }
  241. else {
  242. fragmentSource = baseName.fragment || baseName;
  243. }
  244. var finalVertexCode;
  245. this._loadVertexShaderAsync(vertexSource)
  246. .then(function (vertexCode) {
  247. return _this._processIncludesAsync(vertexCode);
  248. })
  249. .then(function (vertexCodeWithIncludes) {
  250. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  251. return _this._loadFragmentShaderAsync(fragmentSource);
  252. })
  253. .then(function (fragmentCode) {
  254. return _this._processIncludesAsync(fragmentCode);
  255. })
  256. .then(function (fragmentCodeWithIncludes) {
  257. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  258. if (baseName) {
  259. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  260. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  261. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  262. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  263. }
  264. else {
  265. _this._vertexSourceCode = finalVertexCode;
  266. _this._fragmentSourceCode = migratedFragmentCode;
  267. }
  268. _this._setInCache(baseName);
  269. _this._prepareEffect();
  270. });
  271. }
  272. Effect.prototype._getSourceCacheKey = function (baseName) {
  273. var cacheKey = baseName;
  274. if (this._indexParameters) {
  275. for (var key in this._indexParameters) {
  276. if (this._indexParameters.hasOwnProperty(key)) {
  277. cacheKey += "|";
  278. cacheKey += key;
  279. cacheKey += "_";
  280. cacheKey += this._indexParameters[key];
  281. }
  282. }
  283. }
  284. return cacheKey;
  285. };
  286. Effect.prototype._getFromCache = function (baseName) {
  287. if (typeof baseName !== "string") {
  288. return false;
  289. }
  290. var cacheKey = this._getSourceCacheKey(baseName);
  291. var sources = Effect._sourceCache[cacheKey];
  292. if (!sources) {
  293. return false;
  294. }
  295. this._vertexSourceCode = sources.vertex;
  296. this._fragmentSourceCode = sources.fragment;
  297. return true;
  298. };
  299. Effect.prototype._setInCache = function (baseName) {
  300. if (typeof baseName !== "string") {
  301. return;
  302. }
  303. var cacheKey = this._getSourceCacheKey(baseName);
  304. Effect._sourceCache[cacheKey] = {
  305. vertex: this._vertexSourceCode,
  306. fragment: this._fragmentSourceCode
  307. };
  308. };
  309. Object.defineProperty(Effect.prototype, "key", {
  310. /**
  311. * Unique key for this effect
  312. */
  313. get: function () {
  314. return this._key;
  315. },
  316. enumerable: true,
  317. configurable: true
  318. });
  319. /**
  320. * If the effect has been compiled and prepared.
  321. * @returns if the effect is compiled and prepared.
  322. */
  323. Effect.prototype.isReady = function () {
  324. return this._isReady;
  325. };
  326. /**
  327. * The engine the effect was initialized with.
  328. * @returns the engine.
  329. */
  330. Effect.prototype.getEngine = function () {
  331. return this._engine;
  332. };
  333. /**
  334. * The compiled webGL program for the effect
  335. * @returns the webGL program.
  336. */
  337. Effect.prototype.getProgram = function () {
  338. return this._program;
  339. };
  340. /**
  341. * The set of names of attribute variables for the shader.
  342. * @returns An array of attribute names.
  343. */
  344. Effect.prototype.getAttributesNames = function () {
  345. return this._attributesNames;
  346. };
  347. /**
  348. * Returns the attribute at the given index.
  349. * @param index The index of the attribute.
  350. * @returns The location of the attribute.
  351. */
  352. Effect.prototype.getAttributeLocation = function (index) {
  353. return this._attributes[index];
  354. };
  355. /**
  356. * Returns the attribute based on the name of the variable.
  357. * @param name of the attribute to look up.
  358. * @returns the attribute location.
  359. */
  360. Effect.prototype.getAttributeLocationByName = function (name) {
  361. var index = this._attributesNames.indexOf(name);
  362. return this._attributes[index];
  363. };
  364. /**
  365. * The number of attributes.
  366. * @returns the numnber of attributes.
  367. */
  368. Effect.prototype.getAttributesCount = function () {
  369. return this._attributes.length;
  370. };
  371. /**
  372. * Gets the index of a uniform variable.
  373. * @param uniformName of the uniform to look up.
  374. * @returns the index.
  375. */
  376. Effect.prototype.getUniformIndex = function (uniformName) {
  377. return this._uniformsNames.indexOf(uniformName);
  378. };
  379. /**
  380. * Returns the attribute based on the name of the variable.
  381. * @param uniformName of the uniform to look up.
  382. * @returns the location of the uniform.
  383. */
  384. Effect.prototype.getUniform = function (uniformName) {
  385. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  386. };
  387. /**
  388. * Returns an array of sampler variable names
  389. * @returns The array of sampler variable neames.
  390. */
  391. Effect.prototype.getSamplers = function () {
  392. return this._samplers;
  393. };
  394. /**
  395. * The error from the last compilation.
  396. * @returns the error string.
  397. */
  398. Effect.prototype.getCompilationError = function () {
  399. return this._compilationError;
  400. };
  401. /**
  402. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  403. * @param func The callback to be used.
  404. */
  405. Effect.prototype.executeWhenCompiled = function (func) {
  406. if (this.isReady()) {
  407. func(this);
  408. return;
  409. }
  410. this.onCompileObservable.add(function (effect) {
  411. func(effect);
  412. });
  413. };
  414. /** @ignore */
  415. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (vertex instanceof HTMLElement) {
  419. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  420. return Promise.resolve(vertexCode);
  421. }
  422. }
  423. // Base64 encoded ?
  424. if (vertex.substr(0, 7) === "base64:") {
  425. var vertexBinary = window.atob(vertex.substr(7));
  426. return Promise.resolve(vertexBinary);
  427. }
  428. // Is in local store ?
  429. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  430. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  431. }
  432. var vertexShaderUrl;
  433. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  434. vertexShaderUrl = vertex;
  435. }
  436. else {
  437. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  438. }
  439. // Vertex shader
  440. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  441. };
  442. /** @ignore */
  443. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  444. if (BABYLON.Tools.IsWindowObjectExist()) {
  445. // DOM element ?
  446. if (fragment instanceof HTMLElement) {
  447. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  448. return Promise.resolve(fragmentCode);
  449. }
  450. }
  451. // Base64 encoded ?
  452. if (fragment.substr(0, 7) === "base64:") {
  453. var fragmentBinary = window.atob(fragment.substr(7));
  454. return Promise.resolve(fragmentBinary);
  455. }
  456. // Is in local store ?
  457. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  458. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  459. }
  460. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  461. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  462. }
  463. var fragmentShaderUrl;
  464. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  465. fragmentShaderUrl = fragment;
  466. }
  467. else {
  468. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  469. }
  470. // Fragment shader
  471. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  472. };
  473. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  474. // Rebuild shaders source code
  475. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  476. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  477. vertexCode = prefix + vertexCode;
  478. fragmentCode = prefix + fragmentCode;
  479. // Number lines of shaders source code
  480. var i = 2;
  481. var regex = /\n/gm;
  482. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  483. i = 2;
  484. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  485. // Dump shaders name and formatted source code
  486. if (this.name.vertexElement) {
  487. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  488. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  489. }
  490. else if (this.name.vertex) {
  491. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  492. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  493. }
  494. else {
  495. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  496. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  497. }
  498. };
  499. ;
  500. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  501. var preparedSourceCode = this._processPrecision(sourceCode);
  502. if (this._engine.webGLVersion == 1) {
  503. return preparedSourceCode;
  504. }
  505. // Already converted
  506. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  507. return preparedSourceCode.replace("#version 300 es", "");
  508. }
  509. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  510. // Remove extensions
  511. // #extension GL_OES_standard_derivatives : enable
  512. // #extension GL_EXT_shader_texture_lod : enable
  513. // #extension GL_EXT_frag_depth : enable
  514. // #extension GL_EXT_draw_buffers : require
  515. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  516. var result = preparedSourceCode.replace(regex, "");
  517. // Migrate to GLSL v300
  518. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  519. result = result.replace(/attribute[ \t]/g, "in ");
  520. result = result.replace(/[ \t]attribute/g, " in");
  521. if (isFragment) {
  522. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  523. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  524. result = result.replace(/texture2D\s*\(/g, "texture(");
  525. result = result.replace(/textureCube\s*\(/g, "texture(");
  526. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  527. result = result.replace(/gl_FragColor/g, "glFragColor");
  528. result = result.replace(/gl_FragData/g, "glFragData");
  529. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  530. }
  531. return result;
  532. };
  533. Effect.prototype._processIncludesAsync = function (sourceCode) {
  534. var _this = this;
  535. return new Promise(function (resolve, reject) {
  536. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  537. var match = regex.exec(sourceCode);
  538. var returnValue = sourceCode;
  539. while (match != null) {
  540. var includeFile = match[1];
  541. // Uniform declaration
  542. if (includeFile.indexOf("__decl__") !== -1) {
  543. includeFile = includeFile.replace(/__decl__/, "");
  544. if (_this._engine.supportsUniformBuffers) {
  545. includeFile = includeFile.replace(/Vertex/, "Ubo");
  546. includeFile = includeFile.replace(/Fragment/, "Ubo");
  547. }
  548. includeFile = includeFile + "Declaration";
  549. }
  550. if (Effect.IncludesShadersStore[includeFile]) {
  551. // Substitution
  552. var includeContent = Effect.IncludesShadersStore[includeFile];
  553. if (match[2]) {
  554. var splits = match[3].split(",");
  555. for (var index = 0; index < splits.length; index += 2) {
  556. var source = new RegExp(splits[index], "g");
  557. var dest = splits[index + 1];
  558. includeContent = includeContent.replace(source, dest);
  559. }
  560. }
  561. if (match[4]) {
  562. var indexString = match[5];
  563. if (indexString.indexOf("..") !== -1) {
  564. var indexSplits = indexString.split("..");
  565. var minIndex = parseInt(indexSplits[0]);
  566. var maxIndex = parseInt(indexSplits[1]);
  567. var sourceIncludeContent = includeContent.slice(0);
  568. includeContent = "";
  569. if (isNaN(maxIndex)) {
  570. maxIndex = _this._indexParameters[indexSplits[1]];
  571. }
  572. for (var i = minIndex; i < maxIndex; i++) {
  573. if (!_this._engine.supportsUniformBuffers) {
  574. // Ubo replacement
  575. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  576. return p1 + "{X}";
  577. });
  578. }
  579. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  580. }
  581. }
  582. else {
  583. if (!_this._engine.supportsUniformBuffers) {
  584. // Ubo replacement
  585. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  586. return p1 + "{X}";
  587. });
  588. }
  589. includeContent = includeContent.replace(/\{X\}/g, indexString);
  590. }
  591. }
  592. // Replace
  593. returnValue = returnValue.replace(match[0], includeContent);
  594. }
  595. else {
  596. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  597. _this._engine._loadFileAsync(includeShaderUrl)
  598. .then(function (fileContent) {
  599. Effect.IncludesShadersStore[includeFile] = fileContent;
  600. return _this._processIncludesAsync(returnValue);
  601. })
  602. .then(function (returnValue) {
  603. resolve(returnValue);
  604. });
  605. return;
  606. }
  607. match = regex.exec(sourceCode);
  608. }
  609. resolve(returnValue);
  610. });
  611. };
  612. Effect.prototype._processPrecision = function (source) {
  613. if (source.indexOf("precision highp float") === -1) {
  614. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  615. source = "precision mediump float;\n" + source;
  616. }
  617. else {
  618. source = "precision highp float;\n" + source;
  619. }
  620. }
  621. else {
  622. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  623. source = source.replace("precision highp float", "precision mediump float");
  624. }
  625. }
  626. return source;
  627. };
  628. /**
  629. * Recompiles the webGL program
  630. * @param vertexSourceCode The source code for the vertex shader.
  631. * @param fragmentSourceCode The source code for the fragment shader.
  632. * @param onCompiled Callback called when completed.
  633. * @param onError Callback called on error.
  634. */
  635. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  636. var _this = this;
  637. this._isReady = false;
  638. this._vertexSourceCodeOverride = vertexSourceCode;
  639. this._fragmentSourceCodeOverride = fragmentSourceCode;
  640. this.onError = function (effect, error) {
  641. if (onError) {
  642. onError(error);
  643. }
  644. };
  645. this.onCompiled = function () {
  646. var scenes = _this.getEngine().scenes;
  647. for (var i = 0; i < scenes.length; i++) {
  648. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  649. }
  650. if (onCompiled) {
  651. onCompiled(_this._program);
  652. }
  653. };
  654. this._fallbacks = null;
  655. this._prepareEffect();
  656. };
  657. /**
  658. * Gets the uniform locations of the the specified variable names
  659. * @param names THe names of the variables to lookup.
  660. * @returns Array of locations in the same order as variable names.
  661. */
  662. Effect.prototype.getSpecificUniformLocations = function (names) {
  663. var engine = this._engine;
  664. return engine.getUniforms(this._program, names);
  665. };
  666. /**
  667. * Prepares the effect
  668. */
  669. Effect.prototype._prepareEffect = function () {
  670. var attributesNames = this._attributesNames;
  671. var defines = this.defines;
  672. var fallbacks = this._fallbacks;
  673. this._valueCache = {};
  674. var previousProgram = this._program;
  675. try {
  676. var engine = this._engine;
  677. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  678. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  679. }
  680. else {
  681. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  682. }
  683. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  684. if (engine.supportsUniformBuffers) {
  685. for (var name in this._uniformBuffersNames) {
  686. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  687. }
  688. }
  689. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  690. this._attributes = engine.getAttributes(this._program, attributesNames);
  691. var index;
  692. for (index = 0; index < this._samplers.length; index++) {
  693. var sampler = this.getUniform(this._samplers[index]);
  694. if (sampler == null) {
  695. this._samplers.splice(index, 1);
  696. index--;
  697. }
  698. }
  699. engine.bindSamplers(this);
  700. this._compilationError = "";
  701. this._isReady = true;
  702. if (this.onCompiled) {
  703. this.onCompiled(this);
  704. }
  705. this.onCompileObservable.notifyObservers(this);
  706. this.onCompileObservable.clear();
  707. // Unbind mesh reference in fallbacks
  708. if (this._fallbacks) {
  709. this._fallbacks.unBindMesh();
  710. }
  711. if (previousProgram) {
  712. this.getEngine()._deleteProgram(previousProgram);
  713. }
  714. }
  715. catch (e) {
  716. this._compilationError = e.message;
  717. // Let's go through fallbacks then
  718. BABYLON.Tools.Error("Unable to compile effect:");
  719. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  720. return " " + uniform;
  721. }));
  722. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  723. return " " + attribute;
  724. }));
  725. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  726. BABYLON.Tools.Error("Error: " + this._compilationError);
  727. if (previousProgram) {
  728. this._program = previousProgram;
  729. this._isReady = true;
  730. if (this.onError) {
  731. this.onError(this, this._compilationError);
  732. }
  733. this.onErrorObservable.notifyObservers(this);
  734. }
  735. if (fallbacks && fallbacks.isMoreFallbacks) {
  736. BABYLON.Tools.Error("Trying next fallback.");
  737. this.defines = fallbacks.reduce(this.defines, this);
  738. this._prepareEffect();
  739. }
  740. else {
  741. if (this.onError) {
  742. this.onError(this, this._compilationError);
  743. }
  744. this.onErrorObservable.notifyObservers(this);
  745. this.onErrorObservable.clear();
  746. // Unbind mesh reference in fallbacks
  747. if (this._fallbacks) {
  748. this._fallbacks.unBindMesh();
  749. }
  750. }
  751. }
  752. };
  753. Object.defineProperty(Effect.prototype, "isSupported", {
  754. /**
  755. * Checks if the effect is supported. (Must be called after compilation)
  756. */
  757. get: function () {
  758. return this._compilationError === "";
  759. },
  760. enumerable: true,
  761. configurable: true
  762. });
  763. /**
  764. * Binds a texture to the engine to be used as output of the shader.
  765. * @param channel Name of the output variable.
  766. * @param texture Texture to bind.
  767. */
  768. Effect.prototype._bindTexture = function (channel, texture) {
  769. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  770. };
  771. /**
  772. * Sets a texture on the engine to be used in the shader.
  773. * @param channel Name of the sampler variable.
  774. * @param texture Texture to set.
  775. */
  776. Effect.prototype.setTexture = function (channel, texture) {
  777. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  778. };
  779. /**
  780. * Sets an array of textures on the engine to be used in the shader.
  781. * @param channel Name of the variable.
  782. * @param textures Textures to set.
  783. */
  784. Effect.prototype.setTextureArray = function (channel, textures) {
  785. if (this._samplers.indexOf(channel + "Ex") === -1) {
  786. var initialPos = this._samplers.indexOf(channel);
  787. for (var index = 1; index < textures.length; index++) {
  788. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  789. }
  790. }
  791. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  792. };
  793. /**
  794. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  795. * @param channel Name of the sampler variable.
  796. * @param postProcess Post process to get the input texture from.
  797. */
  798. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  799. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  800. };
  801. /** @ignore */
  802. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  803. var cache = this._valueCache[uniformName];
  804. var flag = matrix.updateFlag;
  805. if (cache !== undefined && cache === flag) {
  806. return false;
  807. }
  808. this._valueCache[uniformName] = flag;
  809. return true;
  810. };
  811. /** @ignore */
  812. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  813. var cache = this._valueCache[uniformName];
  814. if (!cache) {
  815. cache = [x, y];
  816. this._valueCache[uniformName] = cache;
  817. return true;
  818. }
  819. var changed = false;
  820. if (cache[0] !== x) {
  821. cache[0] = x;
  822. changed = true;
  823. }
  824. if (cache[1] !== y) {
  825. cache[1] = y;
  826. changed = true;
  827. }
  828. return changed;
  829. };
  830. /** @ignore */
  831. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  832. var cache = this._valueCache[uniformName];
  833. if (!cache) {
  834. cache = [x, y, z];
  835. this._valueCache[uniformName] = cache;
  836. return true;
  837. }
  838. var changed = false;
  839. if (cache[0] !== x) {
  840. cache[0] = x;
  841. changed = true;
  842. }
  843. if (cache[1] !== y) {
  844. cache[1] = y;
  845. changed = true;
  846. }
  847. if (cache[2] !== z) {
  848. cache[2] = z;
  849. changed = true;
  850. }
  851. return changed;
  852. };
  853. /** @ignore */
  854. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  855. var cache = this._valueCache[uniformName];
  856. if (!cache) {
  857. cache = [x, y, z, w];
  858. this._valueCache[uniformName] = cache;
  859. return true;
  860. }
  861. var changed = false;
  862. if (cache[0] !== x) {
  863. cache[0] = x;
  864. changed = true;
  865. }
  866. if (cache[1] !== y) {
  867. cache[1] = y;
  868. changed = true;
  869. }
  870. if (cache[2] !== z) {
  871. cache[2] = z;
  872. changed = true;
  873. }
  874. if (cache[3] !== w) {
  875. cache[3] = w;
  876. changed = true;
  877. }
  878. return changed;
  879. };
  880. /**
  881. * Binds a buffer to a uniform.
  882. * @param buffer Buffer to bind.
  883. * @param name Name of the uniform variable to bind to.
  884. */
  885. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  886. var bufferName = this._uniformBuffersNames[name];
  887. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  888. return;
  889. }
  890. Effect._baseCache[bufferName] = buffer;
  891. this._engine.bindUniformBufferBase(buffer, bufferName);
  892. };
  893. /**
  894. * Binds block to a uniform.
  895. * @param blockName Name of the block to bind.
  896. * @param index Index to bind.
  897. */
  898. Effect.prototype.bindUniformBlock = function (blockName, index) {
  899. this._engine.bindUniformBlock(this._program, blockName, index);
  900. };
  901. /**
  902. * Sets an interger value on a uniform variable.
  903. * @param uniformName Name of the variable.
  904. * @param value Value to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setInt = function (uniformName, value) {
  908. var cache = this._valueCache[uniformName];
  909. if (cache !== undefined && cache === value)
  910. return this;
  911. this._valueCache[uniformName] = value;
  912. this._engine.setInt(this.getUniform(uniformName), value);
  913. return this;
  914. };
  915. /**
  916. * Sets an int array on a uniform variable.
  917. * @param uniformName Name of the variable.
  918. * @param array array to be set.
  919. * @returns this effect.
  920. */
  921. Effect.prototype.setIntArray = function (uniformName, array) {
  922. this._valueCache[uniformName] = null;
  923. this._engine.setIntArray(this.getUniform(uniformName), array);
  924. return this;
  925. };
  926. /**
  927. * 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)
  928. * @param uniformName Name of the variable.
  929. * @param array array to be set.
  930. * @returns this effect.
  931. */
  932. Effect.prototype.setIntArray2 = function (uniformName, array) {
  933. this._valueCache[uniformName] = null;
  934. this._engine.setIntArray2(this.getUniform(uniformName), array);
  935. return this;
  936. };
  937. /**
  938. * 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)
  939. * @param uniformName Name of the variable.
  940. * @param array array to be set.
  941. * @returns this effect.
  942. */
  943. Effect.prototype.setIntArray3 = function (uniformName, array) {
  944. this._valueCache[uniformName] = null;
  945. this._engine.setIntArray3(this.getUniform(uniformName), array);
  946. return this;
  947. };
  948. /**
  949. * 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)
  950. * @param uniformName Name of the variable.
  951. * @param array array to be set.
  952. * @returns this effect.
  953. */
  954. Effect.prototype.setIntArray4 = function (uniformName, array) {
  955. this._valueCache[uniformName] = null;
  956. this._engine.setIntArray4(this.getUniform(uniformName), array);
  957. return this;
  958. };
  959. /**
  960. * Sets an float array on a uniform variable.
  961. * @param uniformName Name of the variable.
  962. * @param array array to be set.
  963. * @returns this effect.
  964. */
  965. Effect.prototype.setFloatArray = function (uniformName, array) {
  966. this._valueCache[uniformName] = null;
  967. this._engine.setFloatArray(this.getUniform(uniformName), array);
  968. return this;
  969. };
  970. /**
  971. * 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)
  972. * @param uniformName Name of the variable.
  973. * @param array array to be set.
  974. * @returns this effect.
  975. */
  976. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  977. this._valueCache[uniformName] = null;
  978. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  979. return this;
  980. };
  981. /**
  982. * 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)
  983. * @param uniformName Name of the variable.
  984. * @param array array to be set.
  985. * @returns this effect.
  986. */
  987. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  988. this._valueCache[uniformName] = null;
  989. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  990. return this;
  991. };
  992. /**
  993. * 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)
  994. * @param uniformName Name of the variable.
  995. * @param array array to be set.
  996. * @returns this effect.
  997. */
  998. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  999. this._valueCache[uniformName] = null;
  1000. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1001. return this;
  1002. };
  1003. /**
  1004. * Sets an array on a uniform variable.
  1005. * @param uniformName Name of the variable.
  1006. * @param array array to be set.
  1007. * @returns this effect.
  1008. */
  1009. Effect.prototype.setArray = function (uniformName, array) {
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setArray(this.getUniform(uniformName), array);
  1012. return this;
  1013. };
  1014. /**
  1015. * 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)
  1016. * @param uniformName Name of the variable.
  1017. * @param array array to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setArray2 = function (uniformName, array) {
  1021. this._valueCache[uniformName] = null;
  1022. this._engine.setArray2(this.getUniform(uniformName), array);
  1023. return this;
  1024. };
  1025. /**
  1026. * 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)
  1027. * @param uniformName Name of the variable.
  1028. * @param array array to be set.
  1029. * @returns this effect.
  1030. */
  1031. Effect.prototype.setArray3 = function (uniformName, array) {
  1032. this._valueCache[uniformName] = null;
  1033. this._engine.setArray3(this.getUniform(uniformName), array);
  1034. return this;
  1035. };
  1036. /**
  1037. * 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)
  1038. * @param uniformName Name of the variable.
  1039. * @param array array to be set.
  1040. * @returns this effect.
  1041. */
  1042. Effect.prototype.setArray4 = function (uniformName, array) {
  1043. this._valueCache[uniformName] = null;
  1044. this._engine.setArray4(this.getUniform(uniformName), array);
  1045. return this;
  1046. };
  1047. /**
  1048. * Sets matrices on a uniform variable.
  1049. * @param uniformName Name of the variable.
  1050. * @param matrices matrices to be set.
  1051. * @returns this effect.
  1052. */
  1053. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1054. if (!matrices) {
  1055. return this;
  1056. }
  1057. this._valueCache[uniformName] = null;
  1058. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1059. return this;
  1060. };
  1061. /**
  1062. * Sets matrix on a uniform variable.
  1063. * @param uniformName Name of the variable.
  1064. * @param matrix matrix to be set.
  1065. * @returns this effect.
  1066. */
  1067. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1068. if (this._cacheMatrix(uniformName, matrix)) {
  1069. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1070. }
  1071. return this;
  1072. };
  1073. /**
  1074. * 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)
  1075. * @param uniformName Name of the variable.
  1076. * @param matrix matrix to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1080. this._valueCache[uniformName] = null;
  1081. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1082. return this;
  1083. };
  1084. /**
  1085. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1086. * @param uniformName Name of the variable.
  1087. * @param matrix matrix to be set.
  1088. * @returns this effect.
  1089. */
  1090. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1091. this._valueCache[uniformName] = null;
  1092. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1093. return this;
  1094. };
  1095. /**
  1096. * Sets a float on a uniform variable.
  1097. * @param uniformName Name of the variable.
  1098. * @param value value to be set.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setFloat = function (uniformName, value) {
  1102. var cache = this._valueCache[uniformName];
  1103. if (cache !== undefined && cache === value)
  1104. return this;
  1105. this._valueCache[uniformName] = value;
  1106. this._engine.setFloat(this.getUniform(uniformName), value);
  1107. return this;
  1108. };
  1109. /**
  1110. * Sets a boolean on a uniform variable.
  1111. * @param uniformName Name of the variable.
  1112. * @param bool value to be set.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setBool = function (uniformName, bool) {
  1116. var cache = this._valueCache[uniformName];
  1117. if (cache !== undefined && cache === bool)
  1118. return this;
  1119. this._valueCache[uniformName] = bool;
  1120. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1121. return this;
  1122. };
  1123. /**
  1124. * Sets a Vector2 on a uniform variable.
  1125. * @param uniformName Name of the variable.
  1126. * @param vector2 vector2 to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1130. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1131. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets a float2 on a uniform variable.
  1137. * @param uniformName Name of the variable.
  1138. * @param x First float in float2.
  1139. * @param y Second float in float2.
  1140. * @returns this effect.
  1141. */
  1142. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1143. if (this._cacheFloat2(uniformName, x, y)) {
  1144. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1145. }
  1146. return this;
  1147. };
  1148. /**
  1149. * Sets a Vector3 on a uniform variable.
  1150. * @param uniformName Name of the variable.
  1151. * @param vector3 Value to be set.
  1152. * @returns this effect.
  1153. */
  1154. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1155. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1156. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1157. }
  1158. return this;
  1159. };
  1160. /**
  1161. * Sets a float3 on a uniform variable.
  1162. * @param uniformName Name of the variable.
  1163. * @param x First float in float3.
  1164. * @param y Second float in float3.
  1165. * @param z Third float in float3.
  1166. * @returns this effect.
  1167. */
  1168. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1169. if (this._cacheFloat3(uniformName, x, y, z)) {
  1170. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1171. }
  1172. return this;
  1173. };
  1174. /**
  1175. * Sets a Vector4 on a uniform variable.
  1176. * @param uniformName Name of the variable.
  1177. * @param vector4 Value to be set.
  1178. * @returns this effect.
  1179. */
  1180. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1181. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1182. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1183. }
  1184. return this;
  1185. };
  1186. /**
  1187. * Sets a float4 on a uniform variable.
  1188. * @param uniformName Name of the variable.
  1189. * @param x First float in float4.
  1190. * @param y Second float in float4.
  1191. * @param z Third float in float4.
  1192. * @param w Fourth float in float4.
  1193. * @returns this effect.
  1194. */
  1195. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1196. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1197. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1198. }
  1199. return this;
  1200. };
  1201. /**
  1202. * Sets a Color3 on a uniform variable.
  1203. * @param uniformName Name of the variable.
  1204. * @param color3 Value to be set.
  1205. * @returns this effect.
  1206. */
  1207. Effect.prototype.setColor3 = function (uniformName, color3) {
  1208. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1209. this._engine.setColor3(this.getUniform(uniformName), color3);
  1210. }
  1211. return this;
  1212. };
  1213. /**
  1214. * Sets a Color4 on a uniform variable.
  1215. * @param uniformName Name of the variable.
  1216. * @param color3 Value to be set.
  1217. * @param alpha Alpha value to be set.
  1218. * @returns this effect.
  1219. */
  1220. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1221. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1222. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1223. }
  1224. return this;
  1225. };
  1226. /**
  1227. * Sets a Color4 on a uniform variable
  1228. * @param uniformName defines the name of the variable
  1229. * @param color4 defines the value to be set
  1230. * @returns this effect.
  1231. */
  1232. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1233. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1234. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1235. }
  1236. return this;
  1237. };
  1238. /**
  1239. * Resets the cache of effects.
  1240. */
  1241. Effect.ResetCache = function () {
  1242. Effect._baseCache = {};
  1243. };
  1244. Effect._uniqueIdSeed = 0;
  1245. Effect._baseCache = {};
  1246. Effect._sourceCache = {};
  1247. // Statics
  1248. /**
  1249. * Store of each shader (The can be looked up using effect.key)
  1250. */
  1251. Effect.ShadersStore = {};
  1252. /**
  1253. * Store of each included file for a shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.IncludesShadersStore = {};
  1256. return Effect;
  1257. }());
  1258. BABYLON.Effect = Effect;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.effect.js.map
  1261. //# sourceMappingURL=babylon.types.js.map
  1262. var BABYLON;
  1263. (function (BABYLON) {
  1264. var KeyboardEventTypes = /** @class */ (function () {
  1265. function KeyboardEventTypes() {
  1266. }
  1267. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1268. get: function () {
  1269. return KeyboardEventTypes._KEYDOWN;
  1270. },
  1271. enumerable: true,
  1272. configurable: true
  1273. });
  1274. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1275. get: function () {
  1276. return KeyboardEventTypes._KEYUP;
  1277. },
  1278. enumerable: true,
  1279. configurable: true
  1280. });
  1281. KeyboardEventTypes._KEYDOWN = 0x01;
  1282. KeyboardEventTypes._KEYUP = 0x02;
  1283. return KeyboardEventTypes;
  1284. }());
  1285. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1286. var KeyboardInfo = /** @class */ (function () {
  1287. function KeyboardInfo(type, event) {
  1288. this.type = type;
  1289. this.event = event;
  1290. }
  1291. return KeyboardInfo;
  1292. }());
  1293. BABYLON.KeyboardInfo = KeyboardInfo;
  1294. /**
  1295. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1296. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1297. */
  1298. var KeyboardInfoPre = /** @class */ (function (_super) {
  1299. __extends(KeyboardInfoPre, _super);
  1300. function KeyboardInfoPre(type, event) {
  1301. var _this = _super.call(this, type, event) || this;
  1302. _this.skipOnPointerObservable = false;
  1303. return _this;
  1304. }
  1305. return KeyboardInfoPre;
  1306. }(KeyboardInfo));
  1307. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1308. })(BABYLON || (BABYLON = {}));
  1309. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1310. var BABYLON;
  1311. (function (BABYLON) {
  1312. var PointerEventTypes = /** @class */ (function () {
  1313. function PointerEventTypes() {
  1314. }
  1315. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1316. get: function () {
  1317. return PointerEventTypes._POINTERDOWN;
  1318. },
  1319. enumerable: true,
  1320. configurable: true
  1321. });
  1322. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1323. get: function () {
  1324. return PointerEventTypes._POINTERUP;
  1325. },
  1326. enumerable: true,
  1327. configurable: true
  1328. });
  1329. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1330. get: function () {
  1331. return PointerEventTypes._POINTERMOVE;
  1332. },
  1333. enumerable: true,
  1334. configurable: true
  1335. });
  1336. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1337. get: function () {
  1338. return PointerEventTypes._POINTERWHEEL;
  1339. },
  1340. enumerable: true,
  1341. configurable: true
  1342. });
  1343. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1344. get: function () {
  1345. return PointerEventTypes._POINTERPICK;
  1346. },
  1347. enumerable: true,
  1348. configurable: true
  1349. });
  1350. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1351. get: function () {
  1352. return PointerEventTypes._POINTERTAP;
  1353. },
  1354. enumerable: true,
  1355. configurable: true
  1356. });
  1357. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1358. get: function () {
  1359. return PointerEventTypes._POINTERDOUBLETAP;
  1360. },
  1361. enumerable: true,
  1362. configurable: true
  1363. });
  1364. PointerEventTypes._POINTERDOWN = 0x01;
  1365. PointerEventTypes._POINTERUP = 0x02;
  1366. PointerEventTypes._POINTERMOVE = 0x04;
  1367. PointerEventTypes._POINTERWHEEL = 0x08;
  1368. PointerEventTypes._POINTERPICK = 0x10;
  1369. PointerEventTypes._POINTERTAP = 0x20;
  1370. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1371. return PointerEventTypes;
  1372. }());
  1373. BABYLON.PointerEventTypes = PointerEventTypes;
  1374. var PointerInfoBase = /** @class */ (function () {
  1375. function PointerInfoBase(type, event) {
  1376. this.type = type;
  1377. this.event = event;
  1378. }
  1379. return PointerInfoBase;
  1380. }());
  1381. BABYLON.PointerInfoBase = PointerInfoBase;
  1382. /**
  1383. * This class is used to store pointer related info for the onPrePointerObservable event.
  1384. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1385. */
  1386. var PointerInfoPre = /** @class */ (function (_super) {
  1387. __extends(PointerInfoPre, _super);
  1388. function PointerInfoPre(type, event, localX, localY) {
  1389. var _this = _super.call(this, type, event) || this;
  1390. _this.skipOnPointerObservable = false;
  1391. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1392. return _this;
  1393. }
  1394. return PointerInfoPre;
  1395. }(PointerInfoBase));
  1396. BABYLON.PointerInfoPre = PointerInfoPre;
  1397. /**
  1398. * This type contains all the data related to a pointer event in Babylon.js.
  1399. * 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.
  1400. */
  1401. var PointerInfo = /** @class */ (function (_super) {
  1402. __extends(PointerInfo, _super);
  1403. function PointerInfo(type, event, pickInfo) {
  1404. var _this = _super.call(this, type, event) || this;
  1405. _this.pickInfo = pickInfo;
  1406. return _this;
  1407. }
  1408. return PointerInfo;
  1409. }(PointerInfoBase));
  1410. BABYLON.PointerInfo = PointerInfo;
  1411. })(BABYLON || (BABYLON = {}));
  1412. //# sourceMappingURL=babylon.pointerEvents.js.map
  1413. var BABYLON;
  1414. (function (BABYLON) {
  1415. BABYLON.ToGammaSpace = 1 / 2.2;
  1416. BABYLON.ToLinearSpace = 2.2;
  1417. BABYLON.Epsilon = 0.001;
  1418. /**
  1419. * Class used to hold a RBG color
  1420. */
  1421. var Color3 = /** @class */ (function () {
  1422. /**
  1423. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1424. * @param r defines the red component (between 0 and 1, default is 0)
  1425. * @param g defines the green component (between 0 and 1, default is 0)
  1426. * @param b defines the blue component (between 0 and 1, default is 0)
  1427. */
  1428. function Color3(
  1429. /**
  1430. * Defines the red component (between 0 and 1, default is 0)
  1431. */
  1432. r,
  1433. /**
  1434. * Defines the green component (between 0 and 1, default is 0)
  1435. */
  1436. g,
  1437. /**
  1438. * Defines the blue component (between 0 and 1, default is 0)
  1439. */
  1440. b) {
  1441. if (r === void 0) { r = 0; }
  1442. if (g === void 0) { g = 0; }
  1443. if (b === void 0) { b = 0; }
  1444. this.r = r;
  1445. this.g = g;
  1446. this.b = b;
  1447. }
  1448. /**
  1449. * Creates a string with the Color3 current values
  1450. * @returns the string representation of the Color3 object
  1451. */
  1452. Color3.prototype.toString = function () {
  1453. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1454. };
  1455. /**
  1456. * Returns the string "Color3"
  1457. * @returns "Color3"
  1458. */
  1459. Color3.prototype.getClassName = function () {
  1460. return "Color3";
  1461. };
  1462. /**
  1463. * Compute the Color3 hash code
  1464. * @returns an unique number that can be used to hash Color3 objects
  1465. */
  1466. Color3.prototype.getHashCode = function () {
  1467. var hash = this.r || 0;
  1468. hash = (hash * 397) ^ (this.g || 0);
  1469. hash = (hash * 397) ^ (this.b || 0);
  1470. return hash;
  1471. };
  1472. // Operators
  1473. /**
  1474. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1475. * @param array defines the array where to store the r,g,b components
  1476. * @param index defines an optional index in the target array to define where to start storing values
  1477. * @returns the current Color3 object
  1478. */
  1479. Color3.prototype.toArray = function (array, index) {
  1480. if (index === undefined) {
  1481. index = 0;
  1482. }
  1483. array[index] = this.r;
  1484. array[index + 1] = this.g;
  1485. array[index + 2] = this.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1490. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1491. * @returns a new {BABYLON.Color4} object
  1492. */
  1493. Color3.prototype.toColor4 = function (alpha) {
  1494. if (alpha === void 0) { alpha = 1; }
  1495. return new Color4(this.r, this.g, this.b, alpha);
  1496. };
  1497. /**
  1498. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1499. * @returns the new array
  1500. */
  1501. Color3.prototype.asArray = function () {
  1502. var result = new Array();
  1503. this.toArray(result, 0);
  1504. return result;
  1505. };
  1506. /**
  1507. * Returns the luminance value
  1508. * @returns a float value
  1509. */
  1510. Color3.prototype.toLuminance = function () {
  1511. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1512. };
  1513. /**
  1514. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1515. * @param otherColor defines the second operand
  1516. * @returns the new Color3 object
  1517. */
  1518. Color3.prototype.multiply = function (otherColor) {
  1519. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1520. };
  1521. /**
  1522. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1523. * @param otherColor defines the second operand
  1524. * @param result defines the Color3 object where to store the result
  1525. * @returns the current Color3
  1526. */
  1527. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1528. result.r = this.r * otherColor.r;
  1529. result.g = this.g * otherColor.g;
  1530. result.b = this.b * otherColor.b;
  1531. return this;
  1532. };
  1533. /**
  1534. * Determines equality between Color3 objects
  1535. * @param otherColor defines the second operand
  1536. * @returns true if the rgb values are equal to the passed ones
  1537. */
  1538. Color3.prototype.equals = function (otherColor) {
  1539. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1540. };
  1541. /**
  1542. * Determines equality between the current Color3 object and a set of r,b,g values
  1543. * @param r defines the red component to check
  1544. * @param g defines the green component to check
  1545. * @param b defines the blue component to check
  1546. * @returns true if the rgb values are equal to the passed ones
  1547. */
  1548. Color3.prototype.equalsFloats = function (r, g, b) {
  1549. return this.r === r && this.g === g && this.b === b;
  1550. };
  1551. /**
  1552. * Multiplies in place each rgb value by scale
  1553. * @param scale defines the scaling factor
  1554. * @returns the updated Color3.
  1555. */
  1556. Color3.prototype.scale = function (scale) {
  1557. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1558. };
  1559. /**
  1560. * Multiplies the rgb values by scale and stores the result into "result"
  1561. * @param scale defines the scaling factor
  1562. * @param result defines the Color3 object where to store the result
  1563. * @returns the unmodified current Color3.
  1564. */
  1565. Color3.prototype.scaleToRef = function (scale, result) {
  1566. result.r = this.r * scale;
  1567. result.g = this.g * scale;
  1568. result.b = this.b * scale;
  1569. return this;
  1570. };
  1571. /**
  1572. * Clamps the rgb values by the min and max values and stores the result into "result"
  1573. * @param min defines minimum clamping value (default is 0)
  1574. * @param max defines maximum clamping value (default is 1)
  1575. * @param result defines color to store the result into
  1576. * @returns the original Color3
  1577. */
  1578. Color3.prototype.clampToRef = function (min, max, result) {
  1579. if (min === void 0) { min = 0; }
  1580. if (max === void 0) { max = 1; }
  1581. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1582. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1583. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1584. return this;
  1585. };
  1586. /**
  1587. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1588. * @param otherColor defines the second operand
  1589. * @returns the new Color3
  1590. */
  1591. Color3.prototype.add = function (otherColor) {
  1592. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1593. };
  1594. /**
  1595. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1596. * @param otherColor defines the second operand
  1597. * @param result defines Color3 object to store the result into
  1598. * @returns the unmodified current Color3
  1599. */
  1600. Color3.prototype.addToRef = function (otherColor, result) {
  1601. result.r = this.r + otherColor.r;
  1602. result.g = this.g + otherColor.g;
  1603. result.b = this.b + otherColor.b;
  1604. return this;
  1605. };
  1606. /**
  1607. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1608. * @param otherColor defines the second operand
  1609. * @returns the new Color3
  1610. */
  1611. Color3.prototype.subtract = function (otherColor) {
  1612. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1613. };
  1614. /**
  1615. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1616. * @param otherColor defines the second operand
  1617. * @param result defines Color3 object to store the result into
  1618. * @returns the unmodified current Color3
  1619. */
  1620. Color3.prototype.subtractToRef = function (otherColor, result) {
  1621. result.r = this.r - otherColor.r;
  1622. result.g = this.g - otherColor.g;
  1623. result.b = this.b - otherColor.b;
  1624. return this;
  1625. };
  1626. /**
  1627. * Copy the current object
  1628. * @returns a new Color3 copied the current one
  1629. */
  1630. Color3.prototype.clone = function () {
  1631. return new Color3(this.r, this.g, this.b);
  1632. };
  1633. /**
  1634. * Copies the rgb values from the source in the current Color3
  1635. * @param source defines the source Color3 object
  1636. * @returns the updated Color3 object
  1637. */
  1638. Color3.prototype.copyFrom = function (source) {
  1639. this.r = source.r;
  1640. this.g = source.g;
  1641. this.b = source.b;
  1642. return this;
  1643. };
  1644. /**
  1645. * Updates the Color3 rgb values from the passed floats
  1646. * @param r defines the red component to read from
  1647. * @param g defines the green component to read from
  1648. * @param b defines the blue component to read from
  1649. * @returns the current Color3 object
  1650. */
  1651. Color3.prototype.copyFromFloats = function (r, g, b) {
  1652. this.r = r;
  1653. this.g = g;
  1654. this.b = b;
  1655. return this;
  1656. };
  1657. /**
  1658. * Updates the Color3 rgb values from the passed floats
  1659. * @param r defines the red component to read from
  1660. * @param g defines the green component to read from
  1661. * @param b defines the blue component to read from
  1662. * @returns the current Color3 object
  1663. */
  1664. Color3.prototype.set = function (r, g, b) {
  1665. return this.copyFromFloats(r, g, b);
  1666. };
  1667. /**
  1668. * Compute the Color3 hexadecimal code as a string
  1669. * @returns a string containing the hexadecimal representation of the Color3 object
  1670. */
  1671. Color3.prototype.toHexString = function () {
  1672. var intR = (this.r * 255) | 0;
  1673. var intG = (this.g * 255) | 0;
  1674. var intB = (this.b * 255) | 0;
  1675. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1676. };
  1677. /**
  1678. * Computes a new Color3 converted from the current one to linear space
  1679. * @returns a new Color3 object
  1680. */
  1681. Color3.prototype.toLinearSpace = function () {
  1682. var convertedColor = new Color3();
  1683. this.toLinearSpaceToRef(convertedColor);
  1684. return convertedColor;
  1685. };
  1686. /**
  1687. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1688. * @param convertedColor defines the Color3 object where to store the linear space version
  1689. * @returns the unmodified Color3
  1690. */
  1691. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1692. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1693. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1694. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1695. return this;
  1696. };
  1697. /**
  1698. * Computes a new Color3 converted from the current one to gamma space
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.prototype.toGammaSpace = function () {
  1702. var convertedColor = new Color3();
  1703. this.toGammaSpaceToRef(convertedColor);
  1704. return convertedColor;
  1705. };
  1706. /**
  1707. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1708. * @param convertedColor defines the Color3 object where to store the gamma space version
  1709. * @returns the unmodified Color3
  1710. */
  1711. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1712. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1713. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1714. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1715. return this;
  1716. };
  1717. // Statics
  1718. /**
  1719. * Creates a new Color3 from the string containing valid hexadecimal values
  1720. * @param hex defines a string containing valid hexadecimal values
  1721. * @returns a new Color3 object
  1722. */
  1723. Color3.FromHexString = function (hex) {
  1724. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1725. return new Color3(0, 0, 0);
  1726. }
  1727. var r = parseInt(hex.substring(1, 3), 16);
  1728. var g = parseInt(hex.substring(3, 5), 16);
  1729. var b = parseInt(hex.substring(5, 7), 16);
  1730. return Color3.FromInts(r, g, b);
  1731. };
  1732. /**
  1733. * Creates a new Vector3 from the starting index of the passed array
  1734. * @param array defines the source array
  1735. * @param offset defines an offset in the source array
  1736. * @returns a new Color3 object
  1737. */
  1738. Color3.FromArray = function (array, offset) {
  1739. if (offset === void 0) { offset = 0; }
  1740. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1741. };
  1742. /**
  1743. * Creates a new Color3 from integer values (< 256)
  1744. * @param r defines the red component to read from (value between 0 and 255)
  1745. * @param g defines the green component to read from (value between 0 and 255)
  1746. * @param b defines the blue component to read from (value between 0 and 255)
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.FromInts = function (r, g, b) {
  1750. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1751. };
  1752. /**
  1753. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1754. * @param start defines the start Color3 value
  1755. * @param end defines the end Color3 value
  1756. * @param amount defines the gradient value between start and end
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Lerp = function (start, end, amount) {
  1760. var r = start.r + ((end.r - start.r) * amount);
  1761. var g = start.g + ((end.g - start.g) * amount);
  1762. var b = start.b + ((end.b - start.b) * amount);
  1763. return new Color3(r, g, b);
  1764. };
  1765. /**
  1766. * Returns a Color3 value containing a red color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Red = function () { return new Color3(1, 0, 0); };
  1770. /**
  1771. * Returns a Color3 value containing a green color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Green = function () { return new Color3(0, 1, 0); };
  1775. /**
  1776. * Returns a Color3 value containing a blue color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1780. /**
  1781. * Returns a Color3 value containing a black color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Black = function () { return new Color3(0, 0, 0); };
  1785. /**
  1786. * Returns a Color3 value containing a white color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.White = function () { return new Color3(1, 1, 1); };
  1790. /**
  1791. * Returns a Color3 value containing a purple color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1795. /**
  1796. * Returns a Color3 value containing a magenta color
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1800. /**
  1801. * Returns a Color3 value containing a yellow color
  1802. * @returns a new Color3 object
  1803. */
  1804. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1805. /**
  1806. * Returns a Color3 value containing a gray color
  1807. * @returns a new Color3 object
  1808. */
  1809. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1810. /**
  1811. * Returns a Color3 value containing a teal color
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1815. /**
  1816. * Returns a Color3 value containing a random color
  1817. * @returns a new Color3 object
  1818. */
  1819. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1820. return Color3;
  1821. }());
  1822. BABYLON.Color3 = Color3;
  1823. /**
  1824. * Class used to hold a RBGA color
  1825. */
  1826. var Color4 = /** @class */ (function () {
  1827. /**
  1828. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1829. * @param r defines the red component (between 0 and 1, default is 0)
  1830. * @param g defines the green component (between 0 and 1, default is 0)
  1831. * @param b defines the blue component (between 0 and 1, default is 0)
  1832. * @param a defines the alpha component (between 0 and 1, default is 1)
  1833. */
  1834. function Color4(
  1835. /**
  1836. * Defines the red component (between 0 and 1, default is 0)
  1837. */
  1838. r,
  1839. /**
  1840. * Defines the green component (between 0 and 1, default is 0)
  1841. */
  1842. g,
  1843. /**
  1844. * Defines the blue component (between 0 and 1, default is 0)
  1845. */
  1846. b,
  1847. /**
  1848. * Defines the alpha component (between 0 and 1, default is 1)
  1849. */
  1850. a) {
  1851. if (r === void 0) { r = 0; }
  1852. if (g === void 0) { g = 0; }
  1853. if (b === void 0) { b = 0; }
  1854. if (a === void 0) { a = 1; }
  1855. this.r = r;
  1856. this.g = g;
  1857. this.b = b;
  1858. this.a = a;
  1859. }
  1860. // Operators
  1861. /**
  1862. * Adds in place the passed Color4 values to the current Color4 object
  1863. * @param right defines the second operand
  1864. * @returns the current updated Color4 object
  1865. */
  1866. Color4.prototype.addInPlace = function (right) {
  1867. this.r += right.r;
  1868. this.g += right.g;
  1869. this.b += right.b;
  1870. this.a += right.a;
  1871. return this;
  1872. };
  1873. /**
  1874. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1875. * @returns the new array
  1876. */
  1877. Color4.prototype.asArray = function () {
  1878. var result = new Array();
  1879. this.toArray(result, 0);
  1880. return result;
  1881. };
  1882. /**
  1883. * Stores from the starting index in the passed array the Color4 successive values
  1884. * @param array defines the array where to store the r,g,b components
  1885. * @param index defines an optional index in the target array to define where to start storing values
  1886. * @returns the current Color4 object
  1887. */
  1888. Color4.prototype.toArray = function (array, index) {
  1889. if (index === undefined) {
  1890. index = 0;
  1891. }
  1892. array[index] = this.r;
  1893. array[index + 1] = this.g;
  1894. array[index + 2] = this.b;
  1895. array[index + 3] = this.a;
  1896. return this;
  1897. };
  1898. /**
  1899. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1900. * @param right defines the second operand
  1901. * @returns a new Color4 object
  1902. */
  1903. Color4.prototype.add = function (right) {
  1904. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1905. };
  1906. /**
  1907. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1908. * @param right defines the second operand
  1909. * @returns a new Color4 object
  1910. */
  1911. Color4.prototype.subtract = function (right) {
  1912. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1913. };
  1914. /**
  1915. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1916. * @param right defines the second operand
  1917. * @param result defines the Color4 object where to store the result
  1918. * @returns the current Color4 object
  1919. */
  1920. Color4.prototype.subtractToRef = function (right, result) {
  1921. result.r = this.r - right.r;
  1922. result.g = this.g - right.g;
  1923. result.b = this.b - right.b;
  1924. result.a = this.a - right.a;
  1925. return this;
  1926. };
  1927. /**
  1928. * Creates a new Color4 with the current Color4 values multiplied by scale
  1929. * @param scale defines the scaling factor to apply
  1930. * @returns a new Color4 object
  1931. */
  1932. Color4.prototype.scale = function (scale) {
  1933. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1934. };
  1935. /**
  1936. * Multiplies the current Color4 values by scale and stores the result in "result"
  1937. * @param scale defines the scaling factor to apply
  1938. * @param result defines the Color4 object where to store the result
  1939. * @returns the current Color4.
  1940. */
  1941. Color4.prototype.scaleToRef = function (scale, result) {
  1942. result.r = this.r * scale;
  1943. result.g = this.g * scale;
  1944. result.b = this.b * scale;
  1945. result.a = this.a * scale;
  1946. return this;
  1947. };
  1948. /**
  1949. * Clamps the rgb values by the min and max values and stores the result into "result"
  1950. * @param min defines minimum clamping value (default is 0)
  1951. * @param max defines maximum clamping value (default is 1)
  1952. * @param result defines color to store the result into.
  1953. * @returns the cuurent Color4
  1954. */
  1955. Color4.prototype.clampToRef = function (min, max, result) {
  1956. if (min === void 0) { min = 0; }
  1957. if (max === void 0) { max = 1; }
  1958. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1959. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1960. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1961. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1962. return this;
  1963. };
  1964. /**
  1965. * Multipy an Color4 value by another and return a new Color4 object
  1966. * @param color defines the Color4 value to multiply by
  1967. * @returns a new Color4 object
  1968. */
  1969. Color4.prototype.multiply = function (color) {
  1970. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1971. };
  1972. /**
  1973. * Multipy a Color4 value by another and push the result in a reference value
  1974. * @param color defines the Color4 value to multiply by
  1975. * @param result defines the Color4 to fill the result in
  1976. * @returns the result Color4
  1977. */
  1978. Color4.prototype.multiplyToRef = function (color, result) {
  1979. result.r = this.r * color.r;
  1980. result.g = this.g * color.g;
  1981. result.b = this.b * color.b;
  1982. result.a = this.a * color.a;
  1983. return result;
  1984. };
  1985. /**
  1986. * Creates a string with the Color4 current values
  1987. * @returns the string representation of the Color4 object
  1988. */
  1989. Color4.prototype.toString = function () {
  1990. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1991. };
  1992. /**
  1993. * Returns the string "Color4"
  1994. * @returns "Color4"
  1995. */
  1996. Color4.prototype.getClassName = function () {
  1997. return "Color4";
  1998. };
  1999. /**
  2000. * Compute the Color4 hash code
  2001. * @returns an unique number that can be used to hash Color4 objects
  2002. */
  2003. Color4.prototype.getHashCode = function () {
  2004. var hash = this.r || 0;
  2005. hash = (hash * 397) ^ (this.g || 0);
  2006. hash = (hash * 397) ^ (this.b || 0);
  2007. hash = (hash * 397) ^ (this.a || 0);
  2008. return hash;
  2009. };
  2010. /**
  2011. * Creates a new Color4 copied from the current one
  2012. * @returns a new Color4 object
  2013. */
  2014. Color4.prototype.clone = function () {
  2015. return new Color4(this.r, this.g, this.b, this.a);
  2016. };
  2017. /**
  2018. * Copies the passed Color4 values into the current one
  2019. * @param source defines the source Color4 object
  2020. * @returns the current updated Color4 object
  2021. */
  2022. Color4.prototype.copyFrom = function (source) {
  2023. this.r = source.r;
  2024. this.g = source.g;
  2025. this.b = source.b;
  2026. this.a = source.a;
  2027. return this;
  2028. };
  2029. /**
  2030. * Copies the passed float values into the current one
  2031. * @param r defines the red component to read from
  2032. * @param g defines the green component to read from
  2033. * @param b defines the blue component to read from
  2034. * @param a defines the alpha component to read from
  2035. * @returns the current updated Color4 object
  2036. */
  2037. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2038. this.r = r;
  2039. this.g = g;
  2040. this.b = b;
  2041. this.a = a;
  2042. return this;
  2043. };
  2044. /**
  2045. * Copies the passed float values into the current one
  2046. * @param r defines the red component to read from
  2047. * @param g defines the green component to read from
  2048. * @param b defines the blue component to read from
  2049. * @param a defines the alpha component to read from
  2050. * @returns the current updated Color4 object
  2051. */
  2052. Color4.prototype.set = function (r, g, b, a) {
  2053. return this.copyFromFloats(r, g, b, a);
  2054. };
  2055. /**
  2056. * Compute the Color4 hexadecimal code as a string
  2057. * @returns a string containing the hexadecimal representation of the Color4 object
  2058. */
  2059. Color4.prototype.toHexString = function () {
  2060. var intR = (this.r * 255) | 0;
  2061. var intG = (this.g * 255) | 0;
  2062. var intB = (this.b * 255) | 0;
  2063. var intA = (this.a * 255) | 0;
  2064. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2065. };
  2066. /**
  2067. * Computes a new Color4 converted from the current one to linear space
  2068. * @returns a new Color4 object
  2069. */
  2070. Color4.prototype.toLinearSpace = function () {
  2071. var convertedColor = new Color4();
  2072. this.toLinearSpaceToRef(convertedColor);
  2073. return convertedColor;
  2074. };
  2075. /**
  2076. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2077. * @param convertedColor defines the Color4 object where to store the linear space version
  2078. * @returns the unmodified Color4
  2079. */
  2080. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2081. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2082. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2083. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2084. convertedColor.a = this.a;
  2085. return this;
  2086. };
  2087. /**
  2088. * Computes a new Color4 converted from the current one to gamma space
  2089. * @returns a new Color4 object
  2090. */
  2091. Color4.prototype.toGammaSpace = function () {
  2092. var convertedColor = new Color4();
  2093. this.toGammaSpaceToRef(convertedColor);
  2094. return convertedColor;
  2095. };
  2096. /**
  2097. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2098. * @param convertedColor defines the Color4 object where to store the gamma space version
  2099. * @returns the unmodified Color4
  2100. */
  2101. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2102. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2103. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2104. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2105. convertedColor.a = this.a;
  2106. return this;
  2107. };
  2108. // Statics
  2109. /**
  2110. * Creates a new Color4 from the string containing valid hexadecimal values
  2111. * @param hex defines a string containing valid hexadecimal values
  2112. * @returns a new Color4 object
  2113. */
  2114. Color4.FromHexString = function (hex) {
  2115. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2116. return new Color4(0.0, 0.0, 0.0, 0.0);
  2117. }
  2118. var r = parseInt(hex.substring(1, 3), 16);
  2119. var g = parseInt(hex.substring(3, 5), 16);
  2120. var b = parseInt(hex.substring(5, 7), 16);
  2121. var a = parseInt(hex.substring(7, 9), 16);
  2122. return Color4.FromInts(r, g, b, a);
  2123. };
  2124. /**
  2125. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2126. * @param left defines the start value
  2127. * @param right defines the end value
  2128. * @param amount defines the gradient factor
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.Lerp = function (left, right, amount) {
  2132. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2133. Color4.LerpToRef(left, right, amount, result);
  2134. return result;
  2135. };
  2136. /**
  2137. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2138. * @param left defines the start value
  2139. * @param right defines the end value
  2140. * @param amount defines the gradient factor
  2141. * @param result defines the Color4 object where to store data
  2142. */
  2143. Color4.LerpToRef = function (left, right, amount, result) {
  2144. result.r = left.r + (right.r - left.r) * amount;
  2145. result.g = left.g + (right.g - left.g) * amount;
  2146. result.b = left.b + (right.b - left.b) * amount;
  2147. result.a = left.a + (right.a - left.a) * amount;
  2148. };
  2149. /**
  2150. * Creates a new Color4 from the starting index element of the passed array
  2151. * @param array defines the source array to read from
  2152. * @param offset defines the offset in the source array
  2153. * @returns a new Color4 object
  2154. */
  2155. Color4.FromArray = function (array, offset) {
  2156. if (offset === void 0) { offset = 0; }
  2157. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2158. };
  2159. /**
  2160. * Creates a new Color3 from integer values (< 256)
  2161. * @param r defines the red component to read from (value between 0 and 255)
  2162. * @param g defines the green component to read from (value between 0 and 255)
  2163. * @param b defines the blue component to read from (value between 0 and 255)
  2164. * @param a defines the alpha component to read from (value between 0 and 255)
  2165. * @returns a new Color3 object
  2166. */
  2167. Color4.FromInts = function (r, g, b, a) {
  2168. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2169. };
  2170. /**
  2171. * Check the content of a given array and convert it to an array containing RGBA data
  2172. * If the original array was already containing count * 4 values then it is returned directly
  2173. * @param colors defines the array to check
  2174. * @param count defines the number of RGBA data to expect
  2175. * @returns an array containing count * 4 values (RGBA)
  2176. */
  2177. Color4.CheckColors4 = function (colors, count) {
  2178. // Check if color3 was used
  2179. if (colors.length === count * 3) {
  2180. var colors4 = [];
  2181. for (var index = 0; index < colors.length; index += 3) {
  2182. var newIndex = (index / 3) * 4;
  2183. colors4[newIndex] = colors[index];
  2184. colors4[newIndex + 1] = colors[index + 1];
  2185. colors4[newIndex + 2] = colors[index + 2];
  2186. colors4[newIndex + 3] = 1.0;
  2187. }
  2188. return colors4;
  2189. }
  2190. return colors;
  2191. };
  2192. return Color4;
  2193. }());
  2194. BABYLON.Color4 = Color4;
  2195. var Vector2 = /** @class */ (function () {
  2196. /**
  2197. * Creates a new Vector2 from the passed x and y coordinates.
  2198. */
  2199. function Vector2(x, y) {
  2200. this.x = x;
  2201. this.y = y;
  2202. }
  2203. /**
  2204. * Returns a string with the Vector2 coordinates.
  2205. */
  2206. Vector2.prototype.toString = function () {
  2207. return "{X: " + this.x + " Y:" + this.y + "}";
  2208. };
  2209. /**
  2210. * Returns the string "Vector2"
  2211. */
  2212. Vector2.prototype.getClassName = function () {
  2213. return "Vector2";
  2214. };
  2215. /**
  2216. * Returns the Vector2 hash code as a number.
  2217. */
  2218. Vector2.prototype.getHashCode = function () {
  2219. var hash = this.x || 0;
  2220. hash = (hash * 397) ^ (this.y || 0);
  2221. return hash;
  2222. };
  2223. // Operators
  2224. /**
  2225. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2226. * Returns the Vector2.
  2227. */
  2228. Vector2.prototype.toArray = function (array, index) {
  2229. if (index === void 0) { index = 0; }
  2230. array[index] = this.x;
  2231. array[index + 1] = this.y;
  2232. return this;
  2233. };
  2234. /**
  2235. * Returns a new array with 2 elements : the Vector2 coordinates.
  2236. */
  2237. Vector2.prototype.asArray = function () {
  2238. var result = new Array();
  2239. this.toArray(result, 0);
  2240. return result;
  2241. };
  2242. /**
  2243. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2244. * Returns the updated Vector2.
  2245. */
  2246. Vector2.prototype.copyFrom = function (source) {
  2247. this.x = source.x;
  2248. this.y = source.y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Sets the Vector2 coordinates with the passed floats.
  2253. * Returns the updated Vector2.
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the passed floats.
  2262. * Returns the updated Vector2.
  2263. */
  2264. Vector2.prototype.set = function (x, y) {
  2265. return this.copyFromFloats(x, y);
  2266. };
  2267. /**
  2268. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2269. */
  2270. Vector2.prototype.add = function (otherVector) {
  2271. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2272. };
  2273. /**
  2274. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2275. * Returns the Vector2.
  2276. */
  2277. Vector2.prototype.addToRef = function (otherVector, result) {
  2278. result.x = this.x + otherVector.x;
  2279. result.y = this.y + otherVector.y;
  2280. return this;
  2281. };
  2282. /**
  2283. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2284. * Returns the updated Vector2.
  2285. */
  2286. Vector2.prototype.addInPlace = function (otherVector) {
  2287. this.x += otherVector.x;
  2288. this.y += otherVector.y;
  2289. return this;
  2290. };
  2291. /**
  2292. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2293. */
  2294. Vector2.prototype.addVector3 = function (otherVector) {
  2295. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2296. };
  2297. /**
  2298. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2299. */
  2300. Vector2.prototype.subtract = function (otherVector) {
  2301. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2302. };
  2303. /**
  2304. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2305. * Returns the Vector2.
  2306. */
  2307. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2308. result.x = this.x - otherVector.x;
  2309. result.y = this.y - otherVector.y;
  2310. return this;
  2311. };
  2312. /**
  2313. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2314. * Returns the updated Vector2.
  2315. */
  2316. Vector2.prototype.subtractInPlace = function (otherVector) {
  2317. this.x -= otherVector.x;
  2318. this.y -= otherVector.y;
  2319. return this;
  2320. };
  2321. /**
  2322. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2323. * Returns the updated Vector2.
  2324. */
  2325. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2326. this.x *= otherVector.x;
  2327. this.y *= otherVector.y;
  2328. return this;
  2329. };
  2330. /**
  2331. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2332. */
  2333. Vector2.prototype.multiply = function (otherVector) {
  2334. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2335. };
  2336. /**
  2337. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2338. * Returns the Vector2.
  2339. */
  2340. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2341. result.x = this.x * otherVector.x;
  2342. result.y = this.y * otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2347. */
  2348. Vector2.prototype.multiplyByFloats = function (x, y) {
  2349. return new Vector2(this.x * x, this.y * y);
  2350. };
  2351. /**
  2352. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2353. */
  2354. Vector2.prototype.divide = function (otherVector) {
  2355. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2356. };
  2357. /**
  2358. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2359. * Returns the Vector2.
  2360. */
  2361. Vector2.prototype.divideToRef = function (otherVector, result) {
  2362. result.x = this.x / otherVector.x;
  2363. result.y = this.y / otherVector.y;
  2364. return this;
  2365. };
  2366. /**
  2367. * Divides the current Vector3 coordinates by the passed ones.
  2368. * Returns the updated Vector3.
  2369. */
  2370. Vector2.prototype.divideInPlace = function (otherVector) {
  2371. return this.divideToRef(otherVector, this);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 with current Vector2 negated coordinates.
  2375. */
  2376. Vector2.prototype.negate = function () {
  2377. return new Vector2(-this.x, -this.y);
  2378. };
  2379. /**
  2380. * Multiply the Vector2 coordinates by scale.
  2381. * Returns the updated Vector2.
  2382. */
  2383. Vector2.prototype.scaleInPlace = function (scale) {
  2384. this.x *= scale;
  2385. this.y *= scale;
  2386. return this;
  2387. };
  2388. /**
  2389. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2390. */
  2391. Vector2.prototype.scale = function (scale) {
  2392. return new Vector2(this.x * scale, this.y * scale);
  2393. };
  2394. /**
  2395. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2396. */
  2397. Vector2.prototype.equals = function (otherVector) {
  2398. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2399. };
  2400. /**
  2401. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2402. */
  2403. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2404. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2405. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2406. };
  2407. // Properties
  2408. /**
  2409. * Returns the vector length (float).
  2410. */
  2411. Vector2.prototype.length = function () {
  2412. return Math.sqrt(this.x * this.x + this.y * this.y);
  2413. };
  2414. /**
  2415. * Returns the vector squared length (float);
  2416. */
  2417. Vector2.prototype.lengthSquared = function () {
  2418. return (this.x * this.x + this.y * this.y);
  2419. };
  2420. // Methods
  2421. /**
  2422. * Normalize the vector.
  2423. * Returns the updated Vector2.
  2424. */
  2425. Vector2.prototype.normalize = function () {
  2426. var len = this.length();
  2427. if (len === 0)
  2428. return this;
  2429. var num = 1.0 / len;
  2430. this.x *= num;
  2431. this.y *= num;
  2432. return this;
  2433. };
  2434. /**
  2435. * Returns a new Vector2 copied from the Vector2.
  2436. */
  2437. Vector2.prototype.clone = function () {
  2438. return new Vector2(this.x, this.y);
  2439. };
  2440. // Statics
  2441. /**
  2442. * Returns a new Vector2(0, 0)
  2443. */
  2444. Vector2.Zero = function () {
  2445. return new Vector2(0, 0);
  2446. };
  2447. /**
  2448. * Returns a new Vector2(1, 1)
  2449. */
  2450. Vector2.One = function () {
  2451. return new Vector2(1, 1);
  2452. };
  2453. /**
  2454. * Returns a new Vector2 set from the passed index element of the passed array.
  2455. */
  2456. Vector2.FromArray = function (array, offset) {
  2457. if (offset === void 0) { offset = 0; }
  2458. return new Vector2(array[offset], array[offset + 1]);
  2459. };
  2460. /**
  2461. * Sets "result" from the passed index element of the passed array.
  2462. */
  2463. Vector2.FromArrayToRef = function (array, offset, result) {
  2464. result.x = array[offset];
  2465. result.y = array[offset + 1];
  2466. };
  2467. /**
  2468. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2469. */
  2470. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2471. var squared = amount * amount;
  2472. var cubed = amount * squared;
  2473. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2474. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2475. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2476. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2477. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2478. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2479. return new Vector2(x, y);
  2480. };
  2481. /**
  2482. * 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".
  2483. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2484. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2485. */
  2486. Vector2.Clamp = function (value, min, max) {
  2487. var x = value.x;
  2488. x = (x > max.x) ? max.x : x;
  2489. x = (x < min.x) ? min.x : x;
  2490. var y = value.y;
  2491. y = (y > max.y) ? max.y : y;
  2492. y = (y < min.y) ? min.y : y;
  2493. return new Vector2(x, y);
  2494. };
  2495. /**
  2496. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2497. */
  2498. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2499. var squared = amount * amount;
  2500. var cubed = amount * squared;
  2501. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2502. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2503. var part3 = (cubed - (2.0 * squared)) + amount;
  2504. var part4 = cubed - squared;
  2505. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2506. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2507. return new Vector2(x, y);
  2508. };
  2509. /**
  2510. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2511. */
  2512. Vector2.Lerp = function (start, end, amount) {
  2513. var x = start.x + ((end.x - start.x) * amount);
  2514. var y = start.y + ((end.y - start.y) * amount);
  2515. return new Vector2(x, y);
  2516. };
  2517. /**
  2518. * Returns the dot product (float) of the vector "left" and the vector "right".
  2519. */
  2520. Vector2.Dot = function (left, right) {
  2521. return left.x * right.x + left.y * right.y;
  2522. };
  2523. /**
  2524. * Returns a new Vector2 equal to the normalized passed vector.
  2525. */
  2526. Vector2.Normalize = function (vector) {
  2527. var newVector = vector.clone();
  2528. newVector.normalize();
  2529. return newVector;
  2530. };
  2531. /**
  2532. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2533. */
  2534. Vector2.Minimize = function (left, right) {
  2535. var x = (left.x < right.x) ? left.x : right.x;
  2536. var y = (left.y < right.y) ? left.y : right.y;
  2537. return new Vector2(x, y);
  2538. };
  2539. /**
  2540. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2541. */
  2542. Vector2.Maximize = function (left, right) {
  2543. var x = (left.x > right.x) ? left.x : right.x;
  2544. var y = (left.y > right.y) ? left.y : right.y;
  2545. return new Vector2(x, y);
  2546. };
  2547. /**
  2548. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2549. */
  2550. Vector2.Transform = function (vector, transformation) {
  2551. var r = Vector2.Zero();
  2552. Vector2.TransformToRef(vector, transformation, r);
  2553. return r;
  2554. };
  2555. /**
  2556. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2557. */
  2558. Vector2.TransformToRef = function (vector, transformation, result) {
  2559. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2560. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2561. result.x = x;
  2562. result.y = y;
  2563. };
  2564. /**
  2565. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2566. */
  2567. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2568. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2569. var sign = a < 0 ? -1 : 1;
  2570. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2571. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2572. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2573. };
  2574. /**
  2575. * Returns the distance (float) between the vectors "value1" and "value2".
  2576. */
  2577. Vector2.Distance = function (value1, value2) {
  2578. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2579. };
  2580. /**
  2581. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2582. */
  2583. Vector2.DistanceSquared = function (value1, value2) {
  2584. var x = value1.x - value2.x;
  2585. var y = value1.y - value2.y;
  2586. return (x * x) + (y * y);
  2587. };
  2588. /**
  2589. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2590. */
  2591. Vector2.Center = function (value1, value2) {
  2592. var center = value1.add(value2);
  2593. center.scaleInPlace(0.5);
  2594. return center;
  2595. };
  2596. /**
  2597. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2598. */
  2599. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2600. var l2 = Vector2.DistanceSquared(segA, segB);
  2601. if (l2 === 0.0) {
  2602. return Vector2.Distance(p, segA);
  2603. }
  2604. var v = segB.subtract(segA);
  2605. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2606. var proj = segA.add(v.multiplyByFloats(t, t));
  2607. return Vector2.Distance(p, proj);
  2608. };
  2609. return Vector2;
  2610. }());
  2611. BABYLON.Vector2 = Vector2;
  2612. /**
  2613. * Classed used to store (x,y,z) vector representation
  2614. * A Vector3 is the main object used in 3D geometry
  2615. * It can represent etiher the coordinates of a point the space, either a direction
  2616. * Reminder: Babylon.js uses a left handed forward facing system
  2617. */
  2618. var Vector3 = /** @class */ (function () {
  2619. /**
  2620. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2621. * @param x defines the first coordinates (on X axis)
  2622. * @param y defines the second coordinates (on Y axis)
  2623. * @param z defines the third coordinates (on Z axis)
  2624. */
  2625. function Vector3(
  2626. /**
  2627. * Defines the first coordinates (on X axis)
  2628. */
  2629. x,
  2630. /**
  2631. * Defines the second coordinates (on Y axis)
  2632. */
  2633. y,
  2634. /**
  2635. * Defines the third coordinates (on Z axis)
  2636. */
  2637. z) {
  2638. this.x = x;
  2639. this.y = y;
  2640. this.z = z;
  2641. }
  2642. /**
  2643. * Creates a string representation of the Vector3
  2644. * @returns a string with the Vector3 coordinates.
  2645. */
  2646. Vector3.prototype.toString = function () {
  2647. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2648. };
  2649. /**
  2650. * Gets the class name
  2651. * @returns the string "Vector3"
  2652. */
  2653. Vector3.prototype.getClassName = function () {
  2654. return "Vector3";
  2655. };
  2656. /**
  2657. * Creates the Vector3 hash code
  2658. * @returns a number which tends to be unique between Vector3 instances
  2659. */
  2660. Vector3.prototype.getHashCode = function () {
  2661. var hash = this.x || 0;
  2662. hash = (hash * 397) ^ (this.y || 0);
  2663. hash = (hash * 397) ^ (this.z || 0);
  2664. return hash;
  2665. };
  2666. // Operators
  2667. /**
  2668. * Creates an array containing three elements : the coordinates of the Vector3
  2669. * @returns a new array of numbers
  2670. */
  2671. Vector3.prototype.asArray = function () {
  2672. var result = [];
  2673. this.toArray(result, 0);
  2674. return result;
  2675. };
  2676. /**
  2677. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2678. * @param array defines the destination array
  2679. * @param index defines the offset in the destination array
  2680. * @returns the current Vector3
  2681. */
  2682. Vector3.prototype.toArray = function (array, index) {
  2683. if (index === void 0) { index = 0; }
  2684. array[index] = this.x;
  2685. array[index + 1] = this.y;
  2686. array[index + 2] = this.z;
  2687. return this;
  2688. };
  2689. /**
  2690. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2691. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2692. */
  2693. Vector3.prototype.toQuaternion = function () {
  2694. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2695. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2696. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2697. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2698. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2699. var cosy = Math.cos(this.y * 0.5);
  2700. var siny = Math.sin(this.y * 0.5);
  2701. result.x = coszMinusx * siny;
  2702. result.y = -sinzMinusx * siny;
  2703. result.z = sinxPlusz * cosy;
  2704. result.w = cosxPlusz * cosy;
  2705. return result;
  2706. };
  2707. /**
  2708. * Adds the passed vector to the current Vector3
  2709. * @param otherVector defines the second operand
  2710. * @returns the current updated Vector3
  2711. */
  2712. Vector3.prototype.addInPlace = function (otherVector) {
  2713. this.x += otherVector.x;
  2714. this.y += otherVector.y;
  2715. this.z += otherVector.z;
  2716. return this;
  2717. };
  2718. /**
  2719. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2720. * @param otherVector defines the second operand
  2721. * @returns the resulting Vector3
  2722. */
  2723. Vector3.prototype.add = function (otherVector) {
  2724. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2725. };
  2726. /**
  2727. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2728. * @param otherVector defines the second operand
  2729. * @param result defines the Vector3 object where to store the result
  2730. * @returns the current Vector3
  2731. */
  2732. Vector3.prototype.addToRef = function (otherVector, result) {
  2733. result.x = this.x + otherVector.x;
  2734. result.y = this.y + otherVector.y;
  2735. result.z = this.z + otherVector.z;
  2736. return this;
  2737. };
  2738. /**
  2739. * Subtract the passed vector from the current Vector3
  2740. * @param otherVector defines the second operand
  2741. * @returns the current updated Vector3
  2742. */
  2743. Vector3.prototype.subtractInPlace = function (otherVector) {
  2744. this.x -= otherVector.x;
  2745. this.y -= otherVector.y;
  2746. this.z -= otherVector.z;
  2747. return this;
  2748. };
  2749. /**
  2750. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2751. * @param otherVector defines the second operand
  2752. * @returns the resulting Vector3
  2753. */
  2754. Vector3.prototype.subtract = function (otherVector) {
  2755. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2756. };
  2757. /**
  2758. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2759. * @param otherVector defines the second operand
  2760. * @param result defines the Vector3 object where to store the result
  2761. * @returns the current Vector3
  2762. */
  2763. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2764. result.x = this.x - otherVector.x;
  2765. result.y = this.y - otherVector.y;
  2766. result.z = this.z - otherVector.z;
  2767. return this;
  2768. };
  2769. /**
  2770. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2771. * @param x defines the x coordinate of the operand
  2772. * @param y defines the y coordinate of the operand
  2773. * @param z defines the z coordinate of the operand
  2774. * @returns the resulting Vector3
  2775. */
  2776. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2777. return new Vector3(this.x - x, this.y - y, this.z - z);
  2778. };
  2779. /**
  2780. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2781. * @param x defines the x coordinate of the operand
  2782. * @param y defines the y coordinate of the operand
  2783. * @param z defines the z coordinate of the operand
  2784. * @param result defines the Vector3 object where to store the result
  2785. * @returns the current Vector3
  2786. */
  2787. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2788. result.x = this.x - x;
  2789. result.y = this.y - y;
  2790. result.z = this.z - z;
  2791. return this;
  2792. };
  2793. /**
  2794. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2795. * @returns a new Vector3
  2796. */
  2797. Vector3.prototype.negate = function () {
  2798. return new Vector3(-this.x, -this.y, -this.z);
  2799. };
  2800. /**
  2801. * Multiplies the Vector3 coordinates by the float "scale"
  2802. * @param scale defines the multiplier factor
  2803. * @returns the current updated Vector3
  2804. */
  2805. Vector3.prototype.scaleInPlace = function (scale) {
  2806. this.x *= scale;
  2807. this.y *= scale;
  2808. this.z *= scale;
  2809. return this;
  2810. };
  2811. /**
  2812. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2813. * @param scale defines the multiplier factor
  2814. * @returns a new Vector3
  2815. */
  2816. Vector3.prototype.scale = function (scale) {
  2817. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2818. };
  2819. /**
  2820. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2821. * @param scale defines the multiplier factor
  2822. * @param result defines the Vector3 object where to store the result
  2823. * @returns the current Vector3
  2824. */
  2825. Vector3.prototype.scaleToRef = function (scale, result) {
  2826. result.x = this.x * scale;
  2827. result.y = this.y * scale;
  2828. result.z = this.z * scale;
  2829. return this;
  2830. };
  2831. /**
  2832. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2833. * @param otherVector defines the second operand
  2834. * @returns true if both vectors are equals
  2835. */
  2836. Vector3.prototype.equals = function (otherVector) {
  2837. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2838. };
  2839. /**
  2840. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2841. * @param otherVector defines the second operand
  2842. * @param epsilon defines the minimal distance to define values as equals
  2843. * @returns true if both vectors are distant less than epsilon
  2844. */
  2845. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2846. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2847. 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);
  2848. };
  2849. /**
  2850. * Returns true if the current Vector3 coordinates equals the passed floats
  2851. * @param x defines the x coordinate of the operand
  2852. * @param y defines the y coordinate of the operand
  2853. * @param z defines the z coordinate of the operand
  2854. * @returns true if both vectors are equals
  2855. */
  2856. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2857. return this.x === x && this.y === y && this.z === z;
  2858. };
  2859. /**
  2860. * Multiplies the current Vector3 coordinates by the passed ones
  2861. * @param otherVector defines the second operand
  2862. * @returns the current updated Vector3
  2863. */
  2864. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2865. this.x *= otherVector.x;
  2866. this.y *= otherVector.y;
  2867. this.z *= otherVector.z;
  2868. return this;
  2869. };
  2870. /**
  2871. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2872. * @param otherVector defines the second operand
  2873. * @returns the new Vector3
  2874. */
  2875. Vector3.prototype.multiply = function (otherVector) {
  2876. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2877. };
  2878. /**
  2879. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2880. * @param otherVector defines the second operand
  2881. * @param result defines the Vector3 object where to store the result
  2882. * @returns the current Vector3
  2883. */
  2884. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2885. result.x = this.x * otherVector.x;
  2886. result.y = this.y * otherVector.y;
  2887. result.z = this.z * otherVector.z;
  2888. return this;
  2889. };
  2890. /**
  2891. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2892. * @param x defines the x coordinate of the operand
  2893. * @param y defines the y coordinate of the operand
  2894. * @param z defines the z coordinate of the operand
  2895. * @returns the new Vector3
  2896. */
  2897. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2898. return new Vector3(this.x * x, this.y * y, this.z * z);
  2899. };
  2900. /**
  2901. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2902. * @param otherVector defines the second operand
  2903. * @returns the new Vector3
  2904. */
  2905. Vector3.prototype.divide = function (otherVector) {
  2906. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2907. };
  2908. /**
  2909. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2910. * @param otherVector defines the second operand
  2911. * @param result defines the Vector3 object where to store the result
  2912. * @returns the current Vector3
  2913. */
  2914. Vector3.prototype.divideToRef = function (otherVector, result) {
  2915. result.x = this.x / otherVector.x;
  2916. result.y = this.y / otherVector.y;
  2917. result.z = this.z / otherVector.z;
  2918. return this;
  2919. };
  2920. /**
  2921. * Divides the current Vector3 coordinates by the passed ones.
  2922. * @param otherVector defines the second operand
  2923. * @returns the current updated Vector3
  2924. */
  2925. Vector3.prototype.divideInPlace = function (otherVector) {
  2926. return this.divideToRef(otherVector, this);
  2927. };
  2928. /**
  2929. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2930. * @param other defines the second operand
  2931. * @returns the current updated Vector3
  2932. */
  2933. Vector3.prototype.minimizeInPlace = function (other) {
  2934. if (other.x < this.x)
  2935. this.x = other.x;
  2936. if (other.y < this.y)
  2937. this.y = other.y;
  2938. if (other.z < this.z)
  2939. this.z = other.z;
  2940. return this;
  2941. };
  2942. /**
  2943. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2944. * @param other defines the second operand
  2945. * @returns the current updated Vector3
  2946. */
  2947. Vector3.prototype.maximizeInPlace = function (other) {
  2948. if (other.x > this.x)
  2949. this.x = other.x;
  2950. if (other.y > this.y)
  2951. this.y = other.y;
  2952. if (other.z > this.z)
  2953. this.z = other.z;
  2954. return this;
  2955. };
  2956. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2957. /**
  2958. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2959. */
  2960. get: function () {
  2961. var absX = Math.abs(this.x);
  2962. var absY = Math.abs(this.y);
  2963. if (absX !== absY) {
  2964. return true;
  2965. }
  2966. var absZ = Math.abs(this.z);
  2967. if (absX !== absZ) {
  2968. return true;
  2969. }
  2970. if (absY !== absZ) {
  2971. return true;
  2972. }
  2973. return false;
  2974. },
  2975. enumerable: true,
  2976. configurable: true
  2977. });
  2978. // Properties
  2979. /**
  2980. * Gets the length of the Vector3
  2981. * @returns the length of the Vecto3
  2982. */
  2983. Vector3.prototype.length = function () {
  2984. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2985. };
  2986. /**
  2987. * Gets the squared length of the Vector3
  2988. * @returns squared length of the Vector3
  2989. */
  2990. Vector3.prototype.lengthSquared = function () {
  2991. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2992. };
  2993. /**
  2994. * Normalize the current Vector3.
  2995. * Please note that this is an in place operation.
  2996. * @returns the current updated Vector3
  2997. */
  2998. Vector3.prototype.normalize = function () {
  2999. var len = this.length();
  3000. if (len === 0 || len === 1.0)
  3001. return this;
  3002. var num = 1.0 / len;
  3003. this.x *= num;
  3004. this.y *= num;
  3005. this.z *= num;
  3006. return this;
  3007. };
  3008. /**
  3009. * Normalize the current Vector3 to a new vector
  3010. * @returns the new Vector3
  3011. */
  3012. Vector3.prototype.normalizeToNew = function () {
  3013. var normalized = new Vector3(0, 0, 0);
  3014. this.normalizeToRef(normalized);
  3015. return normalized;
  3016. };
  3017. /**
  3018. * Normalize the current Vector3 to the reference
  3019. * @param reference define the Vector3 to update
  3020. * @returns the updated Vector3
  3021. */
  3022. Vector3.prototype.normalizeToRef = function (reference) {
  3023. var len = this.length();
  3024. if (len === 0 || len === 1.0) {
  3025. reference.set(this.x, this.y, this.z);
  3026. return reference;
  3027. }
  3028. var scale = 1.0 / len;
  3029. this.scaleToRef(scale, reference);
  3030. return reference;
  3031. };
  3032. /**
  3033. * Creates a new Vector3 copied from the current Vector3
  3034. * @returns the new Vector3
  3035. */
  3036. Vector3.prototype.clone = function () {
  3037. return new Vector3(this.x, this.y, this.z);
  3038. };
  3039. /**
  3040. * Copies the passed vector coordinates to the current Vector3 ones
  3041. * @param source defines the source Vector3
  3042. * @returns the current updated Vector3
  3043. */
  3044. Vector3.prototype.copyFrom = function (source) {
  3045. this.x = source.x;
  3046. this.y = source.y;
  3047. this.z = source.z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Copies the passed floats to the current Vector3 coordinates
  3052. * @param x defines the x coordinate of the operand
  3053. * @param y defines the y coordinate of the operand
  3054. * @param z defines the z coordinate of the operand
  3055. * @returns the current updated Vector3
  3056. */
  3057. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3058. this.x = x;
  3059. this.y = y;
  3060. this.z = z;
  3061. return this;
  3062. };
  3063. /**
  3064. * Copies the passed floats to the current Vector3 coordinates
  3065. * @param x defines the x coordinate of the operand
  3066. * @param y defines the y coordinate of the operand
  3067. * @param z defines the z coordinate of the operand
  3068. * @returns the current updated Vector3
  3069. */
  3070. Vector3.prototype.set = function (x, y, z) {
  3071. return this.copyFromFloats(x, y, z);
  3072. };
  3073. // Statics
  3074. /**
  3075. * Get the clip factor between two vectors
  3076. * @param vector0 defines the first operand
  3077. * @param vector1 defines the second operand
  3078. * @param axis defines the axis to use
  3079. * @param size defines the size along the axis
  3080. * @returns the clip factor
  3081. */
  3082. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3083. var d0 = Vector3.Dot(vector0, axis) - size;
  3084. var d1 = Vector3.Dot(vector1, axis) - size;
  3085. var s = d0 / (d0 - d1);
  3086. return s;
  3087. };
  3088. /**
  3089. * Get angle between two vectors
  3090. * @param vector0 angle between vector0 and vector1
  3091. * @param vector1 angle between vector0 and vector1
  3092. * @param normal direction of the normal
  3093. * @return the angle between vector0 and vector1
  3094. */
  3095. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3096. var v0 = vector0.clone().normalize();
  3097. var v1 = vector1.clone().normalize();
  3098. var dot = Vector3.Dot(v0, v1);
  3099. var n = Vector3.Cross(v0, v1);
  3100. if (Vector3.Dot(n, normal) > 0) {
  3101. return Math.acos(dot);
  3102. }
  3103. return -Math.acos(dot);
  3104. };
  3105. /**
  3106. * Returns a new Vector3 set from the index "offset" of the passed array
  3107. * @param array defines the source array
  3108. * @param offset defines the offset in the source array
  3109. * @returns the new Vector3
  3110. */
  3111. Vector3.FromArray = function (array, offset) {
  3112. if (!offset) {
  3113. offset = 0;
  3114. }
  3115. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3116. };
  3117. /**
  3118. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3119. * This function is deprecated. Use FromArray instead
  3120. * @param array defines the source array
  3121. * @param offset defines the offset in the source array
  3122. * @returns the new Vector3
  3123. */
  3124. Vector3.FromFloatArray = function (array, offset) {
  3125. return Vector3.FromArray(array, offset);
  3126. };
  3127. /**
  3128. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3129. * @param array defines the source array
  3130. * @param offset defines the offset in the source array
  3131. * @param result defines the Vector3 where to store the result
  3132. */
  3133. Vector3.FromArrayToRef = function (array, offset, result) {
  3134. result.x = array[offset];
  3135. result.y = array[offset + 1];
  3136. result.z = array[offset + 2];
  3137. };
  3138. /**
  3139. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3140. * This function is deprecated. Use FromArrayToRef instead.
  3141. * @param array defines the source array
  3142. * @param offset defines the offset in the source array
  3143. * @param result defines the Vector3 where to store the result
  3144. */
  3145. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3146. return Vector3.FromArrayToRef(array, offset, result);
  3147. };
  3148. /**
  3149. * Sets the passed vector "result" with the passed floats.
  3150. * @param x defines the x coordinate of the source
  3151. * @param y defines the y coordinate of the source
  3152. * @param z defines the z coordinate of the source
  3153. * @param result defines the Vector3 where to store the result
  3154. */
  3155. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3156. result.x = x;
  3157. result.y = y;
  3158. result.z = z;
  3159. };
  3160. /**
  3161. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3162. * @returns a new empty Vector3
  3163. */
  3164. Vector3.Zero = function () {
  3165. return new Vector3(0.0, 0.0, 0.0);
  3166. };
  3167. /**
  3168. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3169. * @returns a new unit Vector3
  3170. */
  3171. Vector3.One = function () {
  3172. return new Vector3(1.0, 1.0, 1.0);
  3173. };
  3174. /**
  3175. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3176. * @returns a new up Vector3
  3177. */
  3178. Vector3.Up = function () {
  3179. return new Vector3(0.0, 1.0, 0.0);
  3180. };
  3181. /**
  3182. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3183. * @returns a new forward Vector3
  3184. */
  3185. Vector3.Forward = function () {
  3186. return new Vector3(0.0, 0.0, 1.0);
  3187. };
  3188. /**
  3189. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3190. * @returns a new right Vector3
  3191. */
  3192. Vector3.Right = function () {
  3193. return new Vector3(1.0, 0.0, 0.0);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3197. * @returns a new left Vector3
  3198. */
  3199. Vector3.Left = function () {
  3200. return new Vector3(-1.0, 0.0, 0.0);
  3201. };
  3202. /**
  3203. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3204. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3205. * @param vector defines the Vector3 to transform
  3206. * @param transformation defines the transformation matrix
  3207. * @returns the transformed Vector3
  3208. */
  3209. Vector3.TransformCoordinates = function (vector, transformation) {
  3210. var result = Vector3.Zero();
  3211. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3212. return result;
  3213. };
  3214. /**
  3215. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3216. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3217. * @param vector defines the Vector3 to transform
  3218. * @param transformation defines the transformation matrix
  3219. * @param result defines the Vector3 where to store the result
  3220. */
  3221. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3222. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3223. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3224. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3225. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3226. result.x = x / w;
  3227. result.y = y / w;
  3228. result.z = z / w;
  3229. };
  3230. /**
  3231. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3232. * This method computes tranformed coordinates only, not transformed direction vectors
  3233. * @param x define the x coordinate of the source vector
  3234. * @param y define the y coordinate of the source vector
  3235. * @param z define the z coordinate of the source vector
  3236. * @param transformation defines the transformation matrix
  3237. * @param result defines the Vector3 where to store the result
  3238. */
  3239. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3240. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3241. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3242. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3243. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3244. result.x = rx / rw;
  3245. result.y = ry / rw;
  3246. result.z = rz / rw;
  3247. };
  3248. /**
  3249. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3250. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3251. * @param vector defines the Vector3 to transform
  3252. * @param transformation defines the transformation matrix
  3253. * @returns the new Vector3
  3254. */
  3255. Vector3.TransformNormal = function (vector, transformation) {
  3256. var result = Vector3.Zero();
  3257. Vector3.TransformNormalToRef(vector, transformation, result);
  3258. return result;
  3259. };
  3260. /**
  3261. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3262. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3263. * @param vector defines the Vector3 to transform
  3264. * @param transformation defines the transformation matrix
  3265. * @param result defines the Vector3 where to store the result
  3266. */
  3267. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3268. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3269. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3270. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3271. result.x = x;
  3272. result.y = y;
  3273. result.z = z;
  3274. };
  3275. /**
  3276. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3277. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3278. * @param x define the x coordinate of the source vector
  3279. * @param y define the y coordinate of the source vector
  3280. * @param z define the z coordinate of the source vector
  3281. * @param transformation defines the transformation matrix
  3282. * @param result defines the Vector3 where to store the result
  3283. */
  3284. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3285. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3286. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3287. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3288. };
  3289. /**
  3290. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3291. * @param value1 defines the first control point
  3292. * @param value2 defines the second control point
  3293. * @param value3 defines the third control point
  3294. * @param value4 defines the fourth control point
  3295. * @param amount defines the amount on the spline to use
  3296. * @returns the new Vector3
  3297. */
  3298. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3299. var squared = amount * amount;
  3300. var cubed = amount * squared;
  3301. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3302. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3303. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3304. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3305. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3306. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3307. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3308. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3309. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3310. return new Vector3(x, y, z);
  3311. };
  3312. /**
  3313. * 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"
  3314. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3315. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3316. * @param value defines the current value
  3317. * @param min defines the lower range value
  3318. * @param max defines the upper range value
  3319. * @returns the new Vector3
  3320. */
  3321. Vector3.Clamp = function (value, min, max) {
  3322. var x = value.x;
  3323. x = (x > max.x) ? max.x : x;
  3324. x = (x < min.x) ? min.x : x;
  3325. var y = value.y;
  3326. y = (y > max.y) ? max.y : y;
  3327. y = (y < min.y) ? min.y : y;
  3328. var z = value.z;
  3329. z = (z > max.z) ? max.z : z;
  3330. z = (z < min.z) ? min.z : z;
  3331. return new Vector3(x, y, z);
  3332. };
  3333. /**
  3334. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3335. * @param value1 defines the first control point
  3336. * @param tangent1 defines the first tangent vector
  3337. * @param value2 defines the second control point
  3338. * @param tangent2 defines the second tangent vector
  3339. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3340. * @returns the new Vector3
  3341. */
  3342. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3343. var squared = amount * amount;
  3344. var cubed = amount * squared;
  3345. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3346. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3347. var part3 = (cubed - (2.0 * squared)) + amount;
  3348. var part4 = cubed - squared;
  3349. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3350. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3351. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3352. return new Vector3(x, y, z);
  3353. };
  3354. /**
  3355. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3356. * @param start defines the start value
  3357. * @param end defines the end value
  3358. * @param amount max defines amount between both (between 0 and 1)
  3359. * @returns the new Vector3
  3360. */
  3361. Vector3.Lerp = function (start, end, amount) {
  3362. var result = new Vector3(0, 0, 0);
  3363. Vector3.LerpToRef(start, end, amount, result);
  3364. return result;
  3365. };
  3366. /**
  3367. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3368. * @param start defines the start value
  3369. * @param end defines the end value
  3370. * @param amount max defines amount between both (between 0 and 1)
  3371. * @param result defines the Vector3 where to store the result
  3372. */
  3373. Vector3.LerpToRef = function (start, end, amount, result) {
  3374. result.x = start.x + ((end.x - start.x) * amount);
  3375. result.y = start.y + ((end.y - start.y) * amount);
  3376. result.z = start.z + ((end.z - start.z) * amount);
  3377. };
  3378. /**
  3379. * Returns the dot product (float) between the vectors "left" and "right"
  3380. * @param left defines the left operand
  3381. * @param right defines the right operand
  3382. * @returns the dot product
  3383. */
  3384. Vector3.Dot = function (left, right) {
  3385. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3386. };
  3387. /**
  3388. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3389. * The cross product is then orthogonal to both "left" and "right"
  3390. * @param left defines the left operand
  3391. * @param right defines the right operand
  3392. * @returns the cross product
  3393. */
  3394. Vector3.Cross = function (left, right) {
  3395. var result = Vector3.Zero();
  3396. Vector3.CrossToRef(left, right, result);
  3397. return result;
  3398. };
  3399. /**
  3400. * Sets the passed vector "result" with the cross product of "left" and "right"
  3401. * The cross product is then orthogonal to both "left" and "right"
  3402. * @param left defines the left operand
  3403. * @param right defines the right operand
  3404. * @param result defines the Vector3 where to store the result
  3405. */
  3406. Vector3.CrossToRef = function (left, right, result) {
  3407. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3408. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3409. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3410. result.copyFrom(MathTmp.Vector3[0]);
  3411. };
  3412. /**
  3413. * Returns a new Vector3 as the normalization of the passed vector
  3414. * @param vector defines the Vector3 to normalize
  3415. * @returns the new Vector3
  3416. */
  3417. Vector3.Normalize = function (vector) {
  3418. var result = Vector3.Zero();
  3419. Vector3.NormalizeToRef(vector, result);
  3420. return result;
  3421. };
  3422. /**
  3423. * Sets the passed vector "result" with the normalization of the passed first vector
  3424. * @param vector defines the Vector3 to normalize
  3425. * @param result defines the Vector3 where to store the result
  3426. */
  3427. Vector3.NormalizeToRef = function (vector, result) {
  3428. result.copyFrom(vector);
  3429. result.normalize();
  3430. };
  3431. /**
  3432. * Project a Vector3 onto screen space
  3433. * @param vector defines the Vector3 to project
  3434. * @param world defines the world matrix to use
  3435. * @param transform defines the transform (view x projection) matrix to use
  3436. * @param viewport defines the screen viewport to use
  3437. * @returns the new Vector3
  3438. */
  3439. Vector3.Project = function (vector, world, transform, viewport) {
  3440. var cw = viewport.width;
  3441. var ch = viewport.height;
  3442. var cx = viewport.x;
  3443. var cy = viewport.y;
  3444. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3445. 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);
  3446. var matrix = MathTmp.Matrix[0];
  3447. world.multiplyToRef(transform, matrix);
  3448. matrix.multiplyToRef(viewportMatrix, matrix);
  3449. return Vector3.TransformCoordinates(vector, matrix);
  3450. };
  3451. /**
  3452. * Unproject from screen space to object space
  3453. * @param source defines the screen space Vector3 to use
  3454. * @param viewportWidth defines the current width of the viewport
  3455. * @param viewportHeight defines the current height of the viewport
  3456. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3457. * @param transform defines the transform (view x projection) matrix to use
  3458. * @returns the new Vector3
  3459. */
  3460. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3461. var matrix = MathTmp.Matrix[0];
  3462. world.multiplyToRef(transform, matrix);
  3463. matrix.invert();
  3464. source.x = source.x / viewportWidth * 2 - 1;
  3465. source.y = -(source.y / viewportHeight * 2 - 1);
  3466. var vector = Vector3.TransformCoordinates(source, matrix);
  3467. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3468. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3469. vector = vector.scale(1.0 / num);
  3470. }
  3471. return vector;
  3472. };
  3473. /**
  3474. * Unproject from screen space to object space
  3475. * @param source defines the screen space Vector3 to use
  3476. * @param viewportWidth defines the current width of the viewport
  3477. * @param viewportHeight defines the current height of the viewport
  3478. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3479. * @param view defines the view matrix to use
  3480. * @param projection defines the projection matrix to use
  3481. * @returns the new Vector3
  3482. */
  3483. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3484. var result = Vector3.Zero();
  3485. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3486. return result;
  3487. };
  3488. /**
  3489. * Unproject from screen space to object space
  3490. * @param source defines the screen space Vector3 to use
  3491. * @param viewportWidth defines the current width of the viewport
  3492. * @param viewportHeight defines the current height of the viewport
  3493. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3494. * @param view defines the view matrix to use
  3495. * @param projection defines the projection matrix to use
  3496. * @param result defines the Vector3 where to store the result
  3497. */
  3498. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3499. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3500. };
  3501. /**
  3502. * Unproject from screen space to object space
  3503. * @param sourceX defines the screen space x coordinate to use
  3504. * @param sourceY defines the screen space y coordinate to use
  3505. * @param sourceZ defines the screen space z coordinate to use
  3506. * @param viewportWidth defines the current width of the viewport
  3507. * @param viewportHeight defines the current height of the viewport
  3508. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3509. * @param view defines the view matrix to use
  3510. * @param projection defines the projection matrix to use
  3511. * @param result defines the Vector3 where to store the result
  3512. */
  3513. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3514. var matrix = MathTmp.Matrix[0];
  3515. world.multiplyToRef(view, matrix);
  3516. matrix.multiplyToRef(projection, matrix);
  3517. matrix.invert();
  3518. var screenSource = MathTmp.Vector3[0];
  3519. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3520. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3521. screenSource.z = 2 * sourceZ - 1.0;
  3522. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3523. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3524. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3525. result.scaleInPlace(1.0 / num);
  3526. }
  3527. };
  3528. /**
  3529. * Gets the minimal coordinate values between two Vector3
  3530. * @param left defines the first operand
  3531. * @param right defines the second operand
  3532. * @returns the new Vector3
  3533. */
  3534. Vector3.Minimize = function (left, right) {
  3535. var min = left.clone();
  3536. min.minimizeInPlace(right);
  3537. return min;
  3538. };
  3539. /**
  3540. * Gets the maximal coordinate values between two Vector3
  3541. * @param left defines the first operand
  3542. * @param right defines the second operand
  3543. * @returns the new Vector3
  3544. */
  3545. Vector3.Maximize = function (left, right) {
  3546. var max = left.clone();
  3547. max.maximizeInPlace(right);
  3548. return max;
  3549. };
  3550. /**
  3551. * Returns the distance between the vectors "value1" and "value2"
  3552. * @param value1 defines the first operand
  3553. * @param value2 defines the second operand
  3554. * @returns the distance
  3555. */
  3556. Vector3.Distance = function (value1, value2) {
  3557. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3558. };
  3559. /**
  3560. * Returns the squared distance between the vectors "value1" and "value2"
  3561. * @param value1 defines the first operand
  3562. * @param value2 defines the second operand
  3563. * @returns the squared distance
  3564. */
  3565. Vector3.DistanceSquared = function (value1, value2) {
  3566. var x = value1.x - value2.x;
  3567. var y = value1.y - value2.y;
  3568. var z = value1.z - value2.z;
  3569. return (x * x) + (y * y) + (z * z);
  3570. };
  3571. /**
  3572. * Returns a new Vector3 located at the center between "value1" and "value2"
  3573. * @param value1 defines the first operand
  3574. * @param value2 defines the second operand
  3575. * @returns the new Vector3
  3576. */
  3577. Vector3.Center = function (value1, value2) {
  3578. var center = value1.add(value2);
  3579. center.scaleInPlace(0.5);
  3580. return center;
  3581. };
  3582. /**
  3583. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3584. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3585. * to something in order to rotate it from its local system to the given target system
  3586. * Note: axis1, axis2 and axis3 are normalized during this operation
  3587. * @param axis1 defines the first axis
  3588. * @param axis2 defines the second axis
  3589. * @param axis3 defines the third axis
  3590. * @returns a new Vector3
  3591. */
  3592. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3593. var rotation = Vector3.Zero();
  3594. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3595. return rotation;
  3596. };
  3597. /**
  3598. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3599. * @param axis1 defines the first axis
  3600. * @param axis2 defines the second axis
  3601. * @param axis3 defines the third axis
  3602. * @param ref defines the Vector3 where to store the result
  3603. */
  3604. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3605. var quat = MathTmp.Quaternion[0];
  3606. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3607. quat.toEulerAnglesToRef(ref);
  3608. };
  3609. return Vector3;
  3610. }());
  3611. BABYLON.Vector3 = Vector3;
  3612. //Vector4 class created for EulerAngle class conversion to Quaternion
  3613. var Vector4 = /** @class */ (function () {
  3614. /**
  3615. * Creates a Vector4 object from the passed floats.
  3616. */
  3617. function Vector4(x, y, z, w) {
  3618. this.x = x;
  3619. this.y = y;
  3620. this.z = z;
  3621. this.w = w;
  3622. }
  3623. /**
  3624. * Returns the string with the Vector4 coordinates.
  3625. */
  3626. Vector4.prototype.toString = function () {
  3627. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3628. };
  3629. /**
  3630. * Returns the string "Vector4".
  3631. */
  3632. Vector4.prototype.getClassName = function () {
  3633. return "Vector4";
  3634. };
  3635. /**
  3636. * Returns the Vector4 hash code.
  3637. */
  3638. Vector4.prototype.getHashCode = function () {
  3639. var hash = this.x || 0;
  3640. hash = (hash * 397) ^ (this.y || 0);
  3641. hash = (hash * 397) ^ (this.z || 0);
  3642. hash = (hash * 397) ^ (this.w || 0);
  3643. return hash;
  3644. };
  3645. // Operators
  3646. /**
  3647. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3648. */
  3649. Vector4.prototype.asArray = function () {
  3650. var result = new Array();
  3651. this.toArray(result, 0);
  3652. return result;
  3653. };
  3654. /**
  3655. * Populates the passed array from the passed index with the Vector4 coordinates.
  3656. * Returns the Vector4.
  3657. */
  3658. Vector4.prototype.toArray = function (array, index) {
  3659. if (index === undefined) {
  3660. index = 0;
  3661. }
  3662. array[index] = this.x;
  3663. array[index + 1] = this.y;
  3664. array[index + 2] = this.z;
  3665. array[index + 3] = this.w;
  3666. return this;
  3667. };
  3668. /**
  3669. * Adds the passed vector to the current Vector4.
  3670. * Returns the updated Vector4.
  3671. */
  3672. Vector4.prototype.addInPlace = function (otherVector) {
  3673. this.x += otherVector.x;
  3674. this.y += otherVector.y;
  3675. this.z += otherVector.z;
  3676. this.w += otherVector.w;
  3677. return this;
  3678. };
  3679. /**
  3680. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3681. */
  3682. Vector4.prototype.add = function (otherVector) {
  3683. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3684. };
  3685. /**
  3686. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3687. * Returns the current Vector4.
  3688. */
  3689. Vector4.prototype.addToRef = function (otherVector, result) {
  3690. result.x = this.x + otherVector.x;
  3691. result.y = this.y + otherVector.y;
  3692. result.z = this.z + otherVector.z;
  3693. result.w = this.w + otherVector.w;
  3694. return this;
  3695. };
  3696. /**
  3697. * Subtract in place the passed vector from the current Vector4.
  3698. * Returns the updated Vector4.
  3699. */
  3700. Vector4.prototype.subtractInPlace = function (otherVector) {
  3701. this.x -= otherVector.x;
  3702. this.y -= otherVector.y;
  3703. this.z -= otherVector.z;
  3704. this.w -= otherVector.w;
  3705. return this;
  3706. };
  3707. /**
  3708. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3709. */
  3710. Vector4.prototype.subtract = function (otherVector) {
  3711. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3712. };
  3713. /**
  3714. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3715. * Returns the current Vector4.
  3716. */
  3717. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3718. result.x = this.x - otherVector.x;
  3719. result.y = this.y - otherVector.y;
  3720. result.z = this.z - otherVector.z;
  3721. result.w = this.w - otherVector.w;
  3722. return this;
  3723. };
  3724. /**
  3725. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3726. */
  3727. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3728. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3729. };
  3730. /**
  3731. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3732. * Returns the current Vector4.
  3733. */
  3734. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3735. result.x = this.x - x;
  3736. result.y = this.y - y;
  3737. result.z = this.z - z;
  3738. result.w = this.w - w;
  3739. return this;
  3740. };
  3741. /**
  3742. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3743. */
  3744. Vector4.prototype.negate = function () {
  3745. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3746. };
  3747. /**
  3748. * Multiplies the current Vector4 coordinates by scale (float).
  3749. * Returns the updated Vector4.
  3750. */
  3751. Vector4.prototype.scaleInPlace = function (scale) {
  3752. this.x *= scale;
  3753. this.y *= scale;
  3754. this.z *= scale;
  3755. this.w *= scale;
  3756. return this;
  3757. };
  3758. /**
  3759. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3760. */
  3761. Vector4.prototype.scale = function (scale) {
  3762. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3763. };
  3764. /**
  3765. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3766. * Returns the current Vector4.
  3767. */
  3768. Vector4.prototype.scaleToRef = function (scale, result) {
  3769. result.x = this.x * scale;
  3770. result.y = this.y * scale;
  3771. result.z = this.z * scale;
  3772. result.w = this.w * scale;
  3773. return this;
  3774. };
  3775. /**
  3776. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3777. */
  3778. Vector4.prototype.equals = function (otherVector) {
  3779. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3780. };
  3781. /**
  3782. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3783. */
  3784. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3785. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3786. return otherVector
  3787. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3788. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3789. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3790. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3791. };
  3792. /**
  3793. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3794. */
  3795. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3796. return this.x === x && this.y === y && this.z === z && this.w === w;
  3797. };
  3798. /**
  3799. * Multiplies in place the current Vector4 by the passed one.
  3800. * Returns the updated Vector4.
  3801. */
  3802. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3803. this.x *= otherVector.x;
  3804. this.y *= otherVector.y;
  3805. this.z *= otherVector.z;
  3806. this.w *= otherVector.w;
  3807. return this;
  3808. };
  3809. /**
  3810. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3811. */
  3812. Vector4.prototype.multiply = function (otherVector) {
  3813. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3814. };
  3815. /**
  3816. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3817. * Returns the current Vector4.
  3818. */
  3819. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3820. result.x = this.x * otherVector.x;
  3821. result.y = this.y * otherVector.y;
  3822. result.z = this.z * otherVector.z;
  3823. result.w = this.w * otherVector.w;
  3824. return this;
  3825. };
  3826. /**
  3827. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3828. */
  3829. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3830. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3831. };
  3832. /**
  3833. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3834. */
  3835. Vector4.prototype.divide = function (otherVector) {
  3836. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3837. };
  3838. /**
  3839. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3840. * Returns the current Vector4.
  3841. */
  3842. Vector4.prototype.divideToRef = function (otherVector, result) {
  3843. result.x = this.x / otherVector.x;
  3844. result.y = this.y / otherVector.y;
  3845. result.z = this.z / otherVector.z;
  3846. result.w = this.w / otherVector.w;
  3847. return this;
  3848. };
  3849. /**
  3850. * Divides the current Vector3 coordinates by the passed ones.
  3851. * @returns the updated Vector3.
  3852. */
  3853. Vector4.prototype.divideInPlace = function (otherVector) {
  3854. return this.divideToRef(otherVector, this);
  3855. };
  3856. /**
  3857. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3858. * @param other defines the second operand
  3859. * @returns the current updated Vector4
  3860. */
  3861. Vector4.prototype.minimizeInPlace = function (other) {
  3862. if (other.x < this.x)
  3863. this.x = other.x;
  3864. if (other.y < this.y)
  3865. this.y = other.y;
  3866. if (other.z < this.z)
  3867. this.z = other.z;
  3868. if (other.w < this.w)
  3869. this.w = other.w;
  3870. return this;
  3871. };
  3872. /**
  3873. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3874. * @param other defines the second operand
  3875. * @returns the current updated Vector4
  3876. */
  3877. Vector4.prototype.maximizeInPlace = function (other) {
  3878. if (other.x > this.x)
  3879. this.x = other.x;
  3880. if (other.y > this.y)
  3881. this.y = other.y;
  3882. if (other.z > this.z)
  3883. this.z = other.z;
  3884. if (other.w > this.w)
  3885. this.w = other.w;
  3886. return this;
  3887. };
  3888. // Properties
  3889. /**
  3890. * Returns the Vector4 length (float).
  3891. */
  3892. Vector4.prototype.length = function () {
  3893. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3894. };
  3895. /**
  3896. * Returns the Vector4 squared length (float).
  3897. */
  3898. Vector4.prototype.lengthSquared = function () {
  3899. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3900. };
  3901. // Methods
  3902. /**
  3903. * Normalizes in place the Vector4.
  3904. * Returns the updated Vector4.
  3905. */
  3906. Vector4.prototype.normalize = function () {
  3907. var len = this.length();
  3908. if (len === 0)
  3909. return this;
  3910. var num = 1.0 / len;
  3911. this.x *= num;
  3912. this.y *= num;
  3913. this.z *= num;
  3914. this.w *= num;
  3915. return this;
  3916. };
  3917. /**
  3918. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3919. */
  3920. Vector4.prototype.toVector3 = function () {
  3921. return new Vector3(this.x, this.y, this.z);
  3922. };
  3923. /**
  3924. * Returns a new Vector4 copied from the current one.
  3925. */
  3926. Vector4.prototype.clone = function () {
  3927. return new Vector4(this.x, this.y, this.z, this.w);
  3928. };
  3929. /**
  3930. * Updates the current Vector4 with the passed one coordinates.
  3931. * Returns the updated Vector4.
  3932. */
  3933. Vector4.prototype.copyFrom = function (source) {
  3934. this.x = source.x;
  3935. this.y = source.y;
  3936. this.z = source.z;
  3937. this.w = source.w;
  3938. return this;
  3939. };
  3940. /**
  3941. * Updates the current Vector4 coordinates with the passed floats.
  3942. * Returns the updated Vector4.
  3943. */
  3944. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3945. this.x = x;
  3946. this.y = y;
  3947. this.z = z;
  3948. this.w = w;
  3949. return this;
  3950. };
  3951. /**
  3952. * Updates the current Vector4 coordinates with the passed floats.
  3953. * Returns the updated Vector4.
  3954. */
  3955. Vector4.prototype.set = function (x, y, z, w) {
  3956. return this.copyFromFloats(x, y, z, w);
  3957. };
  3958. // Statics
  3959. /**
  3960. * Returns a new Vector4 set from the starting index of the passed array.
  3961. */
  3962. Vector4.FromArray = function (array, offset) {
  3963. if (!offset) {
  3964. offset = 0;
  3965. }
  3966. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3967. };
  3968. /**
  3969. * Updates the passed vector "result" from the starting index of the passed array.
  3970. */
  3971. Vector4.FromArrayToRef = function (array, offset, result) {
  3972. result.x = array[offset];
  3973. result.y = array[offset + 1];
  3974. result.z = array[offset + 2];
  3975. result.w = array[offset + 3];
  3976. };
  3977. /**
  3978. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3979. */
  3980. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3981. Vector4.FromArrayToRef(array, offset, result);
  3982. };
  3983. /**
  3984. * Updates the passed vector "result" coordinates from the passed floats.
  3985. */
  3986. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3987. result.x = x;
  3988. result.y = y;
  3989. result.z = z;
  3990. result.w = w;
  3991. };
  3992. /**
  3993. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3994. */
  3995. Vector4.Zero = function () {
  3996. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3997. };
  3998. /**
  3999. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4000. */
  4001. Vector4.One = function () {
  4002. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4003. };
  4004. /**
  4005. * Returns a new normalized Vector4 from the passed one.
  4006. */
  4007. Vector4.Normalize = function (vector) {
  4008. var result = Vector4.Zero();
  4009. Vector4.NormalizeToRef(vector, result);
  4010. return result;
  4011. };
  4012. /**
  4013. * Updates the passed vector "result" from the normalization of the passed one.
  4014. */
  4015. Vector4.NormalizeToRef = function (vector, result) {
  4016. result.copyFrom(vector);
  4017. result.normalize();
  4018. };
  4019. Vector4.Minimize = function (left, right) {
  4020. var min = left.clone();
  4021. min.minimizeInPlace(right);
  4022. return min;
  4023. };
  4024. Vector4.Maximize = function (left, right) {
  4025. var max = left.clone();
  4026. max.maximizeInPlace(right);
  4027. return max;
  4028. };
  4029. /**
  4030. * Returns the distance (float) between the vectors "value1" and "value2".
  4031. */
  4032. Vector4.Distance = function (value1, value2) {
  4033. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4034. };
  4035. /**
  4036. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4037. */
  4038. Vector4.DistanceSquared = function (value1, value2) {
  4039. var x = value1.x - value2.x;
  4040. var y = value1.y - value2.y;
  4041. var z = value1.z - value2.z;
  4042. var w = value1.w - value2.w;
  4043. return (x * x) + (y * y) + (z * z) + (w * w);
  4044. };
  4045. /**
  4046. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4047. */
  4048. Vector4.Center = function (value1, value2) {
  4049. var center = value1.add(value2);
  4050. center.scaleInPlace(0.5);
  4051. return center;
  4052. };
  4053. /**
  4054. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4055. * This methods computes transformed normalized direction vectors only.
  4056. */
  4057. Vector4.TransformNormal = function (vector, transformation) {
  4058. var result = Vector4.Zero();
  4059. Vector4.TransformNormalToRef(vector, transformation, result);
  4060. return result;
  4061. };
  4062. /**
  4063. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4064. * This methods computes transformed normalized direction vectors only.
  4065. */
  4066. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4067. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4068. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4069. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4070. result.x = x;
  4071. result.y = y;
  4072. result.z = z;
  4073. result.w = vector.w;
  4074. };
  4075. /**
  4076. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4077. * This methods computes transformed normalized direction vectors only.
  4078. */
  4079. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4080. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4081. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4082. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4083. result.w = w;
  4084. };
  4085. return Vector4;
  4086. }());
  4087. BABYLON.Vector4 = Vector4;
  4088. var Size = /** @class */ (function () {
  4089. /**
  4090. * Creates a Size object from the passed width and height (floats).
  4091. */
  4092. function Size(width, height) {
  4093. this.width = width;
  4094. this.height = height;
  4095. }
  4096. // Returns a string with the Size width and height.
  4097. Size.prototype.toString = function () {
  4098. return "{W: " + this.width + ", H: " + this.height + "}";
  4099. };
  4100. /**
  4101. * Returns the string "Size"
  4102. */
  4103. Size.prototype.getClassName = function () {
  4104. return "Size";
  4105. };
  4106. /**
  4107. * Returns the Size hash code.
  4108. */
  4109. Size.prototype.getHashCode = function () {
  4110. var hash = this.width || 0;
  4111. hash = (hash * 397) ^ (this.height || 0);
  4112. return hash;
  4113. };
  4114. /**
  4115. * Updates the current size from the passed one.
  4116. * Returns the updated Size.
  4117. */
  4118. Size.prototype.copyFrom = function (src) {
  4119. this.width = src.width;
  4120. this.height = src.height;
  4121. };
  4122. /**
  4123. * Updates in place the current Size from the passed floats.
  4124. * Returns the updated Size.
  4125. */
  4126. Size.prototype.copyFromFloats = function (width, height) {
  4127. this.width = width;
  4128. this.height = height;
  4129. return this;
  4130. };
  4131. /**
  4132. * Updates in place the current Size from the passed floats.
  4133. * Returns the updated Size.
  4134. */
  4135. Size.prototype.set = function (width, height) {
  4136. return this.copyFromFloats(width, height);
  4137. };
  4138. /**
  4139. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4140. */
  4141. Size.prototype.multiplyByFloats = function (w, h) {
  4142. return new Size(this.width * w, this.height * h);
  4143. };
  4144. /**
  4145. * Returns a new Size copied from the passed one.
  4146. */
  4147. Size.prototype.clone = function () {
  4148. return new Size(this.width, this.height);
  4149. };
  4150. /**
  4151. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4152. */
  4153. Size.prototype.equals = function (other) {
  4154. if (!other) {
  4155. return false;
  4156. }
  4157. return (this.width === other.width) && (this.height === other.height);
  4158. };
  4159. Object.defineProperty(Size.prototype, "surface", {
  4160. /**
  4161. * Returns the surface of the Size : width * height (float).
  4162. */
  4163. get: function () {
  4164. return this.width * this.height;
  4165. },
  4166. enumerable: true,
  4167. configurable: true
  4168. });
  4169. /**
  4170. * Returns a new Size set to (0.0, 0.0)
  4171. */
  4172. Size.Zero = function () {
  4173. return new Size(0.0, 0.0);
  4174. };
  4175. /**
  4176. * Returns a new Size set as the addition result of the current Size and the passed one.
  4177. */
  4178. Size.prototype.add = function (otherSize) {
  4179. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4180. return r;
  4181. };
  4182. /**
  4183. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4184. */
  4185. Size.prototype.subtract = function (otherSize) {
  4186. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4187. return r;
  4188. };
  4189. /**
  4190. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4191. */
  4192. Size.Lerp = function (start, end, amount) {
  4193. var w = start.width + ((end.width - start.width) * amount);
  4194. var h = start.height + ((end.height - start.height) * amount);
  4195. return new Size(w, h);
  4196. };
  4197. return Size;
  4198. }());
  4199. BABYLON.Size = Size;
  4200. var Quaternion = /** @class */ (function () {
  4201. /**
  4202. * Creates a new Quaternion from the passed floats.
  4203. */
  4204. function Quaternion(x, y, z, w) {
  4205. if (x === void 0) { x = 0.0; }
  4206. if (y === void 0) { y = 0.0; }
  4207. if (z === void 0) { z = 0.0; }
  4208. if (w === void 0) { w = 1.0; }
  4209. this.x = x;
  4210. this.y = y;
  4211. this.z = z;
  4212. this.w = w;
  4213. }
  4214. /**
  4215. * Returns a string with the Quaternion coordinates.
  4216. */
  4217. Quaternion.prototype.toString = function () {
  4218. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4219. };
  4220. /**
  4221. * Returns the string "Quaternion".
  4222. */
  4223. Quaternion.prototype.getClassName = function () {
  4224. return "Quaternion";
  4225. };
  4226. /**
  4227. * Returns the Quaternion hash code.
  4228. */
  4229. Quaternion.prototype.getHashCode = function () {
  4230. var hash = this.x || 0;
  4231. hash = (hash * 397) ^ (this.y || 0);
  4232. hash = (hash * 397) ^ (this.z || 0);
  4233. hash = (hash * 397) ^ (this.w || 0);
  4234. return hash;
  4235. };
  4236. /**
  4237. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4238. */
  4239. Quaternion.prototype.asArray = function () {
  4240. return [this.x, this.y, this.z, this.w];
  4241. };
  4242. /**
  4243. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4244. */
  4245. Quaternion.prototype.equals = function (otherQuaternion) {
  4246. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4247. };
  4248. /**
  4249. * Returns a new Quaternion copied from the current one.
  4250. */
  4251. Quaternion.prototype.clone = function () {
  4252. return new Quaternion(this.x, this.y, this.z, this.w);
  4253. };
  4254. /**
  4255. * Updates the current Quaternion from the passed one coordinates.
  4256. * Returns the updated Quaterion.
  4257. */
  4258. Quaternion.prototype.copyFrom = function (other) {
  4259. this.x = other.x;
  4260. this.y = other.y;
  4261. this.z = other.z;
  4262. this.w = other.w;
  4263. return this;
  4264. };
  4265. /**
  4266. * Updates the current Quaternion from the passed float coordinates.
  4267. * Returns the updated Quaterion.
  4268. */
  4269. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4270. this.x = x;
  4271. this.y = y;
  4272. this.z = z;
  4273. this.w = w;
  4274. return this;
  4275. };
  4276. /**
  4277. * Updates the current Quaternion from the passed float coordinates.
  4278. * Returns the updated Quaterion.
  4279. */
  4280. Quaternion.prototype.set = function (x, y, z, w) {
  4281. return this.copyFromFloats(x, y, z, w);
  4282. };
  4283. /**
  4284. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4285. */
  4286. Quaternion.prototype.add = function (other) {
  4287. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4288. };
  4289. /**
  4290. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4291. */
  4292. Quaternion.prototype.subtract = function (other) {
  4293. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4294. };
  4295. /**
  4296. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4297. */
  4298. Quaternion.prototype.scale = function (value) {
  4299. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4300. };
  4301. /**
  4302. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4303. */
  4304. Quaternion.prototype.multiply = function (q1) {
  4305. var result = new Quaternion(0, 0, 0, 1.0);
  4306. this.multiplyToRef(q1, result);
  4307. return result;
  4308. };
  4309. /**
  4310. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4311. * Returns the current Quaternion.
  4312. */
  4313. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4314. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4315. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4316. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4317. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4318. result.copyFromFloats(x, y, z, w);
  4319. return this;
  4320. };
  4321. /**
  4322. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4323. * Returns the updated Quaternion.
  4324. */
  4325. Quaternion.prototype.multiplyInPlace = function (q1) {
  4326. this.multiplyToRef(q1, this);
  4327. return this;
  4328. };
  4329. /**
  4330. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4331. * Returns the current Quaternion.
  4332. */
  4333. Quaternion.prototype.conjugateToRef = function (ref) {
  4334. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4335. return this;
  4336. };
  4337. /**
  4338. * Conjugates in place the current Quaternion.
  4339. * Returns the updated Quaternion.
  4340. */
  4341. Quaternion.prototype.conjugateInPlace = function () {
  4342. this.x *= -1;
  4343. this.y *= -1;
  4344. this.z *= -1;
  4345. return this;
  4346. };
  4347. /**
  4348. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4349. */
  4350. Quaternion.prototype.conjugate = function () {
  4351. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4352. return result;
  4353. };
  4354. /**
  4355. * Returns the Quaternion length (float).
  4356. */
  4357. Quaternion.prototype.length = function () {
  4358. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4359. };
  4360. /**
  4361. * Normalize in place the current Quaternion.
  4362. * Returns the updated Quaternion.
  4363. */
  4364. Quaternion.prototype.normalize = function () {
  4365. var length = 1.0 / this.length();
  4366. this.x *= length;
  4367. this.y *= length;
  4368. this.z *= length;
  4369. this.w *= length;
  4370. return this;
  4371. };
  4372. /**
  4373. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4374. */
  4375. Quaternion.prototype.toEulerAngles = function (order) {
  4376. if (order === void 0) { order = "YZX"; }
  4377. var result = Vector3.Zero();
  4378. this.toEulerAnglesToRef(result, order);
  4379. return result;
  4380. };
  4381. /**
  4382. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4383. * Returns the current Quaternion.
  4384. */
  4385. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4386. if (order === void 0) { order = "YZX"; }
  4387. var qz = this.z;
  4388. var qx = this.x;
  4389. var qy = this.y;
  4390. var qw = this.w;
  4391. var sqw = qw * qw;
  4392. var sqz = qz * qz;
  4393. var sqx = qx * qx;
  4394. var sqy = qy * qy;
  4395. var zAxisY = qy * qz - qx * qw;
  4396. var limit = .4999999;
  4397. if (zAxisY < -limit) {
  4398. result.y = 2 * Math.atan2(qy, qw);
  4399. result.x = Math.PI / 2;
  4400. result.z = 0;
  4401. }
  4402. else if (zAxisY > limit) {
  4403. result.y = 2 * Math.atan2(qy, qw);
  4404. result.x = -Math.PI / 2;
  4405. result.z = 0;
  4406. }
  4407. else {
  4408. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4409. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4410. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4411. }
  4412. return this;
  4413. };
  4414. /**
  4415. * Updates the passed rotation matrix with the current Quaternion values.
  4416. * Returns the current Quaternion.
  4417. */
  4418. Quaternion.prototype.toRotationMatrix = function (result) {
  4419. var xx = this.x * this.x;
  4420. var yy = this.y * this.y;
  4421. var zz = this.z * this.z;
  4422. var xy = this.x * this.y;
  4423. var zw = this.z * this.w;
  4424. var zx = this.z * this.x;
  4425. var yw = this.y * this.w;
  4426. var yz = this.y * this.z;
  4427. var xw = this.x * this.w;
  4428. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4429. result.m[1] = 2.0 * (xy + zw);
  4430. result.m[2] = 2.0 * (zx - yw);
  4431. result.m[3] = 0;
  4432. result.m[4] = 2.0 * (xy - zw);
  4433. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4434. result.m[6] = 2.0 * (yz + xw);
  4435. result.m[7] = 0;
  4436. result.m[8] = 2.0 * (zx + yw);
  4437. result.m[9] = 2.0 * (yz - xw);
  4438. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4439. result.m[11] = 0;
  4440. result.m[12] = 0;
  4441. result.m[13] = 0;
  4442. result.m[14] = 0;
  4443. result.m[15] = 1.0;
  4444. result._markAsUpdated();
  4445. return this;
  4446. };
  4447. /**
  4448. * Updates the current Quaternion from the passed rotation matrix values.
  4449. * Returns the updated Quaternion.
  4450. */
  4451. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4452. Quaternion.FromRotationMatrixToRef(matrix, this);
  4453. return this;
  4454. };
  4455. // Statics
  4456. /**
  4457. * Returns a new Quaternion set from the passed rotation matrix values.
  4458. */
  4459. Quaternion.FromRotationMatrix = function (matrix) {
  4460. var result = new Quaternion();
  4461. Quaternion.FromRotationMatrixToRef(matrix, result);
  4462. return result;
  4463. };
  4464. /**
  4465. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4466. */
  4467. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4468. var data = matrix.m;
  4469. var m11 = data[0], m12 = data[4], m13 = data[8];
  4470. var m21 = data[1], m22 = data[5], m23 = data[9];
  4471. var m31 = data[2], m32 = data[6], m33 = data[10];
  4472. var trace = m11 + m22 + m33;
  4473. var s;
  4474. if (trace > 0) {
  4475. s = 0.5 / Math.sqrt(trace + 1.0);
  4476. result.w = 0.25 / s;
  4477. result.x = (m32 - m23) * s;
  4478. result.y = (m13 - m31) * s;
  4479. result.z = (m21 - m12) * s;
  4480. }
  4481. else if (m11 > m22 && m11 > m33) {
  4482. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4483. result.w = (m32 - m23) / s;
  4484. result.x = 0.25 * s;
  4485. result.y = (m12 + m21) / s;
  4486. result.z = (m13 + m31) / s;
  4487. }
  4488. else if (m22 > m33) {
  4489. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4490. result.w = (m13 - m31) / s;
  4491. result.x = (m12 + m21) / s;
  4492. result.y = 0.25 * s;
  4493. result.z = (m23 + m32) / s;
  4494. }
  4495. else {
  4496. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4497. result.w = (m21 - m12) / s;
  4498. result.x = (m13 + m31) / s;
  4499. result.y = (m23 + m32) / s;
  4500. result.z = 0.25 * s;
  4501. }
  4502. };
  4503. /**
  4504. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4505. */
  4506. Quaternion.Zero = function () {
  4507. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4508. };
  4509. /**
  4510. * Returns a new Quaternion as the inverted current Quaternion.
  4511. */
  4512. Quaternion.Inverse = function (q) {
  4513. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4514. };
  4515. /**
  4516. * Returns the identity Quaternion.
  4517. */
  4518. Quaternion.Identity = function () {
  4519. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4520. };
  4521. Quaternion.IsIdentity = function (quaternion) {
  4522. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4523. };
  4524. /**
  4525. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4526. */
  4527. Quaternion.RotationAxis = function (axis, angle) {
  4528. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4529. };
  4530. /**
  4531. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4532. */
  4533. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4534. var sin = Math.sin(angle / 2);
  4535. axis.normalize();
  4536. result.w = Math.cos(angle / 2);
  4537. result.x = axis.x * sin;
  4538. result.y = axis.y * sin;
  4539. result.z = axis.z * sin;
  4540. return result;
  4541. };
  4542. /**
  4543. * Retuns a new Quaternion set from the starting index of the passed array.
  4544. */
  4545. Quaternion.FromArray = function (array, offset) {
  4546. if (!offset) {
  4547. offset = 0;
  4548. }
  4549. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4550. };
  4551. /**
  4552. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4553. */
  4554. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4555. var q = new Quaternion();
  4556. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4557. return q;
  4558. };
  4559. /**
  4560. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4561. */
  4562. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4563. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4564. var halfRoll = roll * 0.5;
  4565. var halfPitch = pitch * 0.5;
  4566. var halfYaw = yaw * 0.5;
  4567. var sinRoll = Math.sin(halfRoll);
  4568. var cosRoll = Math.cos(halfRoll);
  4569. var sinPitch = Math.sin(halfPitch);
  4570. var cosPitch = Math.cos(halfPitch);
  4571. var sinYaw = Math.sin(halfYaw);
  4572. var cosYaw = Math.cos(halfYaw);
  4573. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4574. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4575. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4576. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4577. };
  4578. /**
  4579. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4580. */
  4581. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4582. var result = new Quaternion();
  4583. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4584. return result;
  4585. };
  4586. /**
  4587. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4588. */
  4589. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4590. // Produces a quaternion from Euler angles in the z-x-z orientation
  4591. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4592. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4593. var halfBeta = beta * 0.5;
  4594. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4595. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4596. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4597. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4598. };
  4599. /**
  4600. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4601. * cf to Vector3.RotationFromAxis() documentation.
  4602. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4603. */
  4604. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4605. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4606. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4607. return quat;
  4608. };
  4609. /**
  4610. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4611. * cf to Vector3.RotationFromAxis() documentation.
  4612. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4613. */
  4614. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4615. var rotMat = MathTmp.Matrix[0];
  4616. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4617. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4618. };
  4619. Quaternion.Slerp = function (left, right, amount) {
  4620. var result = Quaternion.Identity();
  4621. Quaternion.SlerpToRef(left, right, amount, result);
  4622. return result;
  4623. };
  4624. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4625. var num2;
  4626. var num3;
  4627. var num = amount;
  4628. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4629. var flag = false;
  4630. if (num4 < 0) {
  4631. flag = true;
  4632. num4 = -num4;
  4633. }
  4634. if (num4 > 0.999999) {
  4635. num3 = 1 - num;
  4636. num2 = flag ? -num : num;
  4637. }
  4638. else {
  4639. var num5 = Math.acos(num4);
  4640. var num6 = (1.0 / Math.sin(num5));
  4641. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4642. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4643. }
  4644. result.x = (num3 * left.x) + (num2 * right.x);
  4645. result.y = (num3 * left.y) + (num2 * right.y);
  4646. result.z = (num3 * left.z) + (num2 * right.z);
  4647. result.w = (num3 * left.w) + (num2 * right.w);
  4648. };
  4649. /**
  4650. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4651. */
  4652. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4653. var squared = amount * amount;
  4654. var cubed = amount * squared;
  4655. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4656. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4657. var part3 = (cubed - (2.0 * squared)) + amount;
  4658. var part4 = cubed - squared;
  4659. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4660. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4661. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4662. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4663. return new Quaternion(x, y, z, w);
  4664. };
  4665. return Quaternion;
  4666. }());
  4667. BABYLON.Quaternion = Quaternion;
  4668. var Matrix = /** @class */ (function () {
  4669. function Matrix() {
  4670. this._isIdentity = false;
  4671. this._isIdentityDirty = true;
  4672. this.m = new Float32Array(16);
  4673. this._markAsUpdated();
  4674. }
  4675. Matrix.prototype._markAsUpdated = function () {
  4676. this.updateFlag = Matrix._updateFlagSeed++;
  4677. this._isIdentityDirty = true;
  4678. };
  4679. // Properties
  4680. /**
  4681. * Boolean : True is the matrix is the identity matrix
  4682. */
  4683. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4684. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4685. if (this._isIdentityDirty) {
  4686. this._isIdentityDirty = false;
  4687. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4688. this._isIdentity = false;
  4689. }
  4690. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4691. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4692. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4693. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4694. this._isIdentity = false;
  4695. }
  4696. else {
  4697. this._isIdentity = true;
  4698. }
  4699. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4700. this._isIdentity = false;
  4701. }
  4702. }
  4703. return this._isIdentity;
  4704. };
  4705. /**
  4706. * Returns the matrix determinant (float).
  4707. */
  4708. Matrix.prototype.determinant = function () {
  4709. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4710. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4711. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4712. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4713. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4714. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4715. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4716. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4717. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4718. };
  4719. // Methods
  4720. /**
  4721. * Returns the matrix underlying array.
  4722. */
  4723. Matrix.prototype.toArray = function () {
  4724. return this.m;
  4725. };
  4726. /**
  4727. * Returns the matrix underlying array.
  4728. */
  4729. Matrix.prototype.asArray = function () {
  4730. return this.toArray();
  4731. };
  4732. /**
  4733. * Inverts in place the Matrix.
  4734. * Returns the Matrix inverted.
  4735. */
  4736. Matrix.prototype.invert = function () {
  4737. this.invertToRef(this);
  4738. return this;
  4739. };
  4740. /**
  4741. * Sets all the matrix elements to zero.
  4742. * Returns the Matrix.
  4743. */
  4744. Matrix.prototype.reset = function () {
  4745. for (var index = 0; index < 16; index++) {
  4746. this.m[index] = 0.0;
  4747. }
  4748. this._markAsUpdated();
  4749. return this;
  4750. };
  4751. /**
  4752. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4753. */
  4754. Matrix.prototype.add = function (other) {
  4755. var result = new Matrix();
  4756. this.addToRef(other, result);
  4757. return result;
  4758. };
  4759. /**
  4760. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4761. * Returns the Matrix.
  4762. */
  4763. Matrix.prototype.addToRef = function (other, result) {
  4764. for (var index = 0; index < 16; index++) {
  4765. result.m[index] = this.m[index] + other.m[index];
  4766. }
  4767. result._markAsUpdated();
  4768. return this;
  4769. };
  4770. /**
  4771. * Adds in place the passed matrix to the current Matrix.
  4772. * Returns the updated Matrix.
  4773. */
  4774. Matrix.prototype.addToSelf = function (other) {
  4775. for (var index = 0; index < 16; index++) {
  4776. this.m[index] += other.m[index];
  4777. }
  4778. this._markAsUpdated();
  4779. return this;
  4780. };
  4781. /**
  4782. * Sets the passed matrix with the current inverted Matrix.
  4783. * Returns the unmodified current Matrix.
  4784. */
  4785. Matrix.prototype.invertToRef = function (other) {
  4786. var l1 = this.m[0];
  4787. var l2 = this.m[1];
  4788. var l3 = this.m[2];
  4789. var l4 = this.m[3];
  4790. var l5 = this.m[4];
  4791. var l6 = this.m[5];
  4792. var l7 = this.m[6];
  4793. var l8 = this.m[7];
  4794. var l9 = this.m[8];
  4795. var l10 = this.m[9];
  4796. var l11 = this.m[10];
  4797. var l12 = this.m[11];
  4798. var l13 = this.m[12];
  4799. var l14 = this.m[13];
  4800. var l15 = this.m[14];
  4801. var l16 = this.m[15];
  4802. var l17 = (l11 * l16) - (l12 * l15);
  4803. var l18 = (l10 * l16) - (l12 * l14);
  4804. var l19 = (l10 * l15) - (l11 * l14);
  4805. var l20 = (l9 * l16) - (l12 * l13);
  4806. var l21 = (l9 * l15) - (l11 * l13);
  4807. var l22 = (l9 * l14) - (l10 * l13);
  4808. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4809. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4810. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4811. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4812. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4813. var l28 = (l7 * l16) - (l8 * l15);
  4814. var l29 = (l6 * l16) - (l8 * l14);
  4815. var l30 = (l6 * l15) - (l7 * l14);
  4816. var l31 = (l5 * l16) - (l8 * l13);
  4817. var l32 = (l5 * l15) - (l7 * l13);
  4818. var l33 = (l5 * l14) - (l6 * l13);
  4819. var l34 = (l7 * l12) - (l8 * l11);
  4820. var l35 = (l6 * l12) - (l8 * l10);
  4821. var l36 = (l6 * l11) - (l7 * l10);
  4822. var l37 = (l5 * l12) - (l8 * l9);
  4823. var l38 = (l5 * l11) - (l7 * l9);
  4824. var l39 = (l5 * l10) - (l6 * l9);
  4825. other.m[0] = l23 * l27;
  4826. other.m[4] = l24 * l27;
  4827. other.m[8] = l25 * l27;
  4828. other.m[12] = l26 * l27;
  4829. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4830. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4831. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4832. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4833. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4834. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4835. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4836. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4837. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4838. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4839. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4840. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4841. other._markAsUpdated();
  4842. return this;
  4843. };
  4844. /**
  4845. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4846. * Returns the updated Matrix.
  4847. */
  4848. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4849. this.m[12] = x;
  4850. this.m[13] = y;
  4851. this.m[14] = z;
  4852. this._markAsUpdated();
  4853. return this;
  4854. };
  4855. /**
  4856. * Inserts the translation vector in the current Matrix.
  4857. * Returns the updated Matrix.
  4858. */
  4859. Matrix.prototype.setTranslation = function (vector3) {
  4860. this.m[12] = vector3.x;
  4861. this.m[13] = vector3.y;
  4862. this.m[14] = vector3.z;
  4863. this._markAsUpdated();
  4864. return this;
  4865. };
  4866. /**
  4867. * Returns a new Vector3 as the extracted translation from the Matrix.
  4868. */
  4869. Matrix.prototype.getTranslation = function () {
  4870. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4871. };
  4872. /**
  4873. * Fill a Vector3 with the extracted translation from the Matrix.
  4874. */
  4875. Matrix.prototype.getTranslationToRef = function (result) {
  4876. result.x = this.m[12];
  4877. result.y = this.m[13];
  4878. result.z = this.m[14];
  4879. return this;
  4880. };
  4881. /**
  4882. * Remove rotation and scaling part from the Matrix.
  4883. * Returns the updated Matrix.
  4884. */
  4885. Matrix.prototype.removeRotationAndScaling = function () {
  4886. this.setRowFromFloats(0, 1, 0, 0, 0);
  4887. this.setRowFromFloats(1, 0, 1, 0, 0);
  4888. this.setRowFromFloats(2, 0, 0, 1, 0);
  4889. return this;
  4890. };
  4891. /**
  4892. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4893. */
  4894. Matrix.prototype.multiply = function (other) {
  4895. var result = new Matrix();
  4896. this.multiplyToRef(other, result);
  4897. return result;
  4898. };
  4899. /**
  4900. * Updates the current Matrix from the passed one values.
  4901. * Returns the updated Matrix.
  4902. */
  4903. Matrix.prototype.copyFrom = function (other) {
  4904. for (var index = 0; index < 16; index++) {
  4905. this.m[index] = other.m[index];
  4906. }
  4907. this._markAsUpdated();
  4908. return this;
  4909. };
  4910. /**
  4911. * Populates the passed array from the starting index with the Matrix values.
  4912. * Returns the Matrix.
  4913. */
  4914. Matrix.prototype.copyToArray = function (array, offset) {
  4915. if (offset === void 0) { offset = 0; }
  4916. for (var index = 0; index < 16; index++) {
  4917. array[offset + index] = this.m[index];
  4918. }
  4919. return this;
  4920. };
  4921. /**
  4922. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4923. */
  4924. Matrix.prototype.multiplyToRef = function (other, result) {
  4925. this.multiplyToArray(other, result.m, 0);
  4926. result._markAsUpdated();
  4927. return this;
  4928. };
  4929. /**
  4930. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4931. */
  4932. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4933. var tm0 = this.m[0];
  4934. var tm1 = this.m[1];
  4935. var tm2 = this.m[2];
  4936. var tm3 = this.m[3];
  4937. var tm4 = this.m[4];
  4938. var tm5 = this.m[5];
  4939. var tm6 = this.m[6];
  4940. var tm7 = this.m[7];
  4941. var tm8 = this.m[8];
  4942. var tm9 = this.m[9];
  4943. var tm10 = this.m[10];
  4944. var tm11 = this.m[11];
  4945. var tm12 = this.m[12];
  4946. var tm13 = this.m[13];
  4947. var tm14 = this.m[14];
  4948. var tm15 = this.m[15];
  4949. var om0 = other.m[0];
  4950. var om1 = other.m[1];
  4951. var om2 = other.m[2];
  4952. var om3 = other.m[3];
  4953. var om4 = other.m[4];
  4954. var om5 = other.m[5];
  4955. var om6 = other.m[6];
  4956. var om7 = other.m[7];
  4957. var om8 = other.m[8];
  4958. var om9 = other.m[9];
  4959. var om10 = other.m[10];
  4960. var om11 = other.m[11];
  4961. var om12 = other.m[12];
  4962. var om13 = other.m[13];
  4963. var om14 = other.m[14];
  4964. var om15 = other.m[15];
  4965. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4966. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4967. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4968. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4969. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4970. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4971. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4972. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4973. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4974. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4975. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4976. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4977. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4978. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4979. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4980. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4981. return this;
  4982. };
  4983. /**
  4984. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4985. */
  4986. Matrix.prototype.equals = function (value) {
  4987. return value &&
  4988. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4989. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4990. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4991. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4992. };
  4993. /**
  4994. * Returns a new Matrix from the current Matrix.
  4995. */
  4996. Matrix.prototype.clone = function () {
  4997. 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]);
  4998. };
  4999. /**
  5000. * Returns the string "Matrix"
  5001. */
  5002. Matrix.prototype.getClassName = function () {
  5003. return "Matrix";
  5004. };
  5005. /**
  5006. * Returns the Matrix hash code.
  5007. */
  5008. Matrix.prototype.getHashCode = function () {
  5009. var hash = this.m[0] || 0;
  5010. for (var i = 1; i < 16; i++) {
  5011. hash = (hash * 397) ^ (this.m[i] || 0);
  5012. }
  5013. return hash;
  5014. };
  5015. /**
  5016. * Decomposes the current Matrix into :
  5017. * - a scale vector3 passed as a reference to update,
  5018. * - a rotation quaternion passed as a reference to update,
  5019. * - a translation vector3 passed as a reference to update.
  5020. * Returns the true if operation was successful.
  5021. */
  5022. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5023. translation.x = this.m[12];
  5024. translation.y = this.m[13];
  5025. translation.z = this.m[14];
  5026. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5027. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5028. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5029. if (this.determinant() <= 0) {
  5030. scale.y *= -1;
  5031. }
  5032. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5033. rotation.x = 0;
  5034. rotation.y = 0;
  5035. rotation.z = 0;
  5036. rotation.w = 1;
  5037. return false;
  5038. }
  5039. 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]);
  5040. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5041. return true;
  5042. };
  5043. /**
  5044. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5045. * @param ref matrix to store the result
  5046. */
  5047. Matrix.prototype.toNormalMatrix = function (ref) {
  5048. this.invertToRef(ref);
  5049. ref.transpose();
  5050. var m = ref.m;
  5051. 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);
  5052. };
  5053. /**
  5054. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5055. */
  5056. Matrix.prototype.getRotationMatrix = function () {
  5057. var result = Matrix.Identity();
  5058. this.getRotationMatrixToRef(result);
  5059. return result;
  5060. };
  5061. /**
  5062. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5063. * Returns the current Matrix.
  5064. */
  5065. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5066. var m = this.m;
  5067. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5068. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5069. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5070. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5071. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5072. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5073. 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);
  5074. return this;
  5075. };
  5076. // Statics
  5077. /**
  5078. * Returns a new Matrix set from the starting index of the passed array.
  5079. */
  5080. Matrix.FromArray = function (array, offset) {
  5081. var result = new Matrix();
  5082. if (!offset) {
  5083. offset = 0;
  5084. }
  5085. Matrix.FromArrayToRef(array, offset, result);
  5086. return result;
  5087. };
  5088. /**
  5089. * Sets the passed "result" matrix from the starting index of the passed array.
  5090. */
  5091. Matrix.FromArrayToRef = function (array, offset, result) {
  5092. for (var index = 0; index < 16; index++) {
  5093. result.m[index] = array[index + offset];
  5094. }
  5095. result._markAsUpdated();
  5096. };
  5097. /**
  5098. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5099. */
  5100. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5101. for (var index = 0; index < 16; index++) {
  5102. result.m[index] = array[index + offset] * scale;
  5103. }
  5104. result._markAsUpdated();
  5105. };
  5106. /**
  5107. * Sets the passed matrix "result" with the 16 passed floats.
  5108. */
  5109. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5110. result.m[0] = initialM11;
  5111. result.m[1] = initialM12;
  5112. result.m[2] = initialM13;
  5113. result.m[3] = initialM14;
  5114. result.m[4] = initialM21;
  5115. result.m[5] = initialM22;
  5116. result.m[6] = initialM23;
  5117. result.m[7] = initialM24;
  5118. result.m[8] = initialM31;
  5119. result.m[9] = initialM32;
  5120. result.m[10] = initialM33;
  5121. result.m[11] = initialM34;
  5122. result.m[12] = initialM41;
  5123. result.m[13] = initialM42;
  5124. result.m[14] = initialM43;
  5125. result.m[15] = initialM44;
  5126. result._markAsUpdated();
  5127. };
  5128. /**
  5129. * Returns the index-th row of the current matrix as a new Vector4.
  5130. */
  5131. Matrix.prototype.getRow = function (index) {
  5132. if (index < 0 || index > 3) {
  5133. return null;
  5134. }
  5135. var i = index * 4;
  5136. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5137. };
  5138. /**
  5139. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5140. * Returns the updated Matrix.
  5141. */
  5142. Matrix.prototype.setRow = function (index, row) {
  5143. if (index < 0 || index > 3) {
  5144. return this;
  5145. }
  5146. var i = index * 4;
  5147. this.m[i + 0] = row.x;
  5148. this.m[i + 1] = row.y;
  5149. this.m[i + 2] = row.z;
  5150. this.m[i + 3] = row.w;
  5151. this._markAsUpdated();
  5152. return this;
  5153. };
  5154. /**
  5155. * Compute the transpose of the matrix.
  5156. * Returns a new Matrix.
  5157. */
  5158. Matrix.prototype.transpose = function () {
  5159. return Matrix.Transpose(this);
  5160. };
  5161. /**
  5162. * Compute the transpose of the matrix.
  5163. * Returns the current matrix.
  5164. */
  5165. Matrix.prototype.transposeToRef = function (result) {
  5166. Matrix.TransposeToRef(this, result);
  5167. return this;
  5168. };
  5169. /**
  5170. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5171. * Returns the updated Matrix.
  5172. */
  5173. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5174. if (index < 0 || index > 3) {
  5175. return this;
  5176. }
  5177. var i = index * 4;
  5178. this.m[i + 0] = x;
  5179. this.m[i + 1] = y;
  5180. this.m[i + 2] = z;
  5181. this.m[i + 3] = w;
  5182. this._markAsUpdated();
  5183. return this;
  5184. };
  5185. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5186. /**
  5187. * Static identity matrix to be used as readonly matrix
  5188. * Must not be updated.
  5189. */
  5190. get: function () {
  5191. return Matrix._identityReadOnly;
  5192. },
  5193. enumerable: true,
  5194. configurable: true
  5195. });
  5196. /**
  5197. * Returns a new Matrix set from the 16 passed floats.
  5198. */
  5199. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5200. var result = new Matrix();
  5201. result.m[0] = initialM11;
  5202. result.m[1] = initialM12;
  5203. result.m[2] = initialM13;
  5204. result.m[3] = initialM14;
  5205. result.m[4] = initialM21;
  5206. result.m[5] = initialM22;
  5207. result.m[6] = initialM23;
  5208. result.m[7] = initialM24;
  5209. result.m[8] = initialM31;
  5210. result.m[9] = initialM32;
  5211. result.m[10] = initialM33;
  5212. result.m[11] = initialM34;
  5213. result.m[12] = initialM41;
  5214. result.m[13] = initialM42;
  5215. result.m[14] = initialM43;
  5216. result.m[15] = initialM44;
  5217. return result;
  5218. };
  5219. /**
  5220. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5221. */
  5222. Matrix.Compose = function (scale, rotation, translation) {
  5223. var result = Matrix.Identity();
  5224. Matrix.ComposeToRef(scale, rotation, translation, result);
  5225. return result;
  5226. };
  5227. /**
  5228. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5229. */
  5230. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5231. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5232. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5233. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5234. result.setTranslation(translation);
  5235. };
  5236. /**
  5237. * Returns a new indentity Matrix.
  5238. */
  5239. Matrix.Identity = function () {
  5240. 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);
  5241. };
  5242. /**
  5243. * Sets the passed "result" as an identity matrix.
  5244. */
  5245. Matrix.IdentityToRef = function (result) {
  5246. 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);
  5247. };
  5248. /**
  5249. * Returns a new zero Matrix.
  5250. */
  5251. Matrix.Zero = function () {
  5252. 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);
  5253. };
  5254. /**
  5255. * Returns a new rotation matrix for "angle" radians around the X axis.
  5256. */
  5257. Matrix.RotationX = function (angle) {
  5258. var result = new Matrix();
  5259. Matrix.RotationXToRef(angle, result);
  5260. return result;
  5261. };
  5262. /**
  5263. * Returns a new Matrix as the passed inverted one.
  5264. */
  5265. Matrix.Invert = function (source) {
  5266. var result = new Matrix();
  5267. source.invertToRef(result);
  5268. return result;
  5269. };
  5270. /**
  5271. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5272. */
  5273. Matrix.RotationXToRef = function (angle, result) {
  5274. var s = Math.sin(angle);
  5275. var c = Math.cos(angle);
  5276. result.m[0] = 1.0;
  5277. result.m[15] = 1.0;
  5278. result.m[5] = c;
  5279. result.m[10] = c;
  5280. result.m[9] = -s;
  5281. result.m[6] = s;
  5282. result.m[1] = 0.0;
  5283. result.m[2] = 0.0;
  5284. result.m[3] = 0.0;
  5285. result.m[4] = 0.0;
  5286. result.m[7] = 0.0;
  5287. result.m[8] = 0.0;
  5288. result.m[11] = 0.0;
  5289. result.m[12] = 0.0;
  5290. result.m[13] = 0.0;
  5291. result.m[14] = 0.0;
  5292. result._markAsUpdated();
  5293. };
  5294. /**
  5295. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5296. */
  5297. Matrix.RotationY = function (angle) {
  5298. var result = new Matrix();
  5299. Matrix.RotationYToRef(angle, result);
  5300. return result;
  5301. };
  5302. /**
  5303. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5304. */
  5305. Matrix.RotationYToRef = function (angle, result) {
  5306. var s = Math.sin(angle);
  5307. var c = Math.cos(angle);
  5308. result.m[5] = 1.0;
  5309. result.m[15] = 1.0;
  5310. result.m[0] = c;
  5311. result.m[2] = -s;
  5312. result.m[8] = s;
  5313. result.m[10] = c;
  5314. result.m[1] = 0.0;
  5315. result.m[3] = 0.0;
  5316. result.m[4] = 0.0;
  5317. result.m[6] = 0.0;
  5318. result.m[7] = 0.0;
  5319. result.m[9] = 0.0;
  5320. result.m[11] = 0.0;
  5321. result.m[12] = 0.0;
  5322. result.m[13] = 0.0;
  5323. result.m[14] = 0.0;
  5324. result._markAsUpdated();
  5325. };
  5326. /**
  5327. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5328. */
  5329. Matrix.RotationZ = function (angle) {
  5330. var result = new Matrix();
  5331. Matrix.RotationZToRef(angle, result);
  5332. return result;
  5333. };
  5334. /**
  5335. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5336. */
  5337. Matrix.RotationZToRef = function (angle, result) {
  5338. var s = Math.sin(angle);
  5339. var c = Math.cos(angle);
  5340. result.m[10] = 1.0;
  5341. result.m[15] = 1.0;
  5342. result.m[0] = c;
  5343. result.m[1] = s;
  5344. result.m[4] = -s;
  5345. result.m[5] = c;
  5346. result.m[2] = 0.0;
  5347. result.m[3] = 0.0;
  5348. result.m[6] = 0.0;
  5349. result.m[7] = 0.0;
  5350. result.m[8] = 0.0;
  5351. result.m[9] = 0.0;
  5352. result.m[11] = 0.0;
  5353. result.m[12] = 0.0;
  5354. result.m[13] = 0.0;
  5355. result.m[14] = 0.0;
  5356. result._markAsUpdated();
  5357. };
  5358. /**
  5359. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5360. */
  5361. Matrix.RotationAxis = function (axis, angle) {
  5362. var result = Matrix.Zero();
  5363. Matrix.RotationAxisToRef(axis, angle, result);
  5364. return result;
  5365. };
  5366. /**
  5367. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5368. */
  5369. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5370. var s = Math.sin(-angle);
  5371. var c = Math.cos(-angle);
  5372. var c1 = 1 - c;
  5373. axis.normalize();
  5374. result.m[0] = (axis.x * axis.x) * c1 + c;
  5375. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5376. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5377. result.m[3] = 0.0;
  5378. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5379. result.m[5] = (axis.y * axis.y) * c1 + c;
  5380. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5381. result.m[7] = 0.0;
  5382. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5383. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5384. result.m[10] = (axis.z * axis.z) * c1 + c;
  5385. result.m[11] = 0.0;
  5386. result.m[15] = 1.0;
  5387. result._markAsUpdated();
  5388. };
  5389. /**
  5390. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5391. */
  5392. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5393. var result = new Matrix();
  5394. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5395. return result;
  5396. };
  5397. /**
  5398. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5399. */
  5400. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5401. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5402. this._tempQuaternion.toRotationMatrix(result);
  5403. };
  5404. /**
  5405. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5406. */
  5407. Matrix.Scaling = function (x, y, z) {
  5408. var result = Matrix.Zero();
  5409. Matrix.ScalingToRef(x, y, z, result);
  5410. return result;
  5411. };
  5412. /**
  5413. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5414. */
  5415. Matrix.ScalingToRef = function (x, y, z, result) {
  5416. result.m[0] = x;
  5417. result.m[1] = 0.0;
  5418. result.m[2] = 0.0;
  5419. result.m[3] = 0.0;
  5420. result.m[4] = 0.0;
  5421. result.m[5] = y;
  5422. result.m[6] = 0.0;
  5423. result.m[7] = 0.0;
  5424. result.m[8] = 0.0;
  5425. result.m[9] = 0.0;
  5426. result.m[10] = z;
  5427. result.m[11] = 0.0;
  5428. result.m[12] = 0.0;
  5429. result.m[13] = 0.0;
  5430. result.m[14] = 0.0;
  5431. result.m[15] = 1.0;
  5432. result._markAsUpdated();
  5433. };
  5434. /**
  5435. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5436. */
  5437. Matrix.Translation = function (x, y, z) {
  5438. var result = Matrix.Identity();
  5439. Matrix.TranslationToRef(x, y, z, result);
  5440. return result;
  5441. };
  5442. /**
  5443. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5444. */
  5445. Matrix.TranslationToRef = function (x, y, z, result) {
  5446. 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);
  5447. };
  5448. /**
  5449. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5450. * @param startValue defines the start value
  5451. * @param endValue defines the end value
  5452. * @param gradient defines the gradient factor
  5453. * @returns the new matrix
  5454. */
  5455. Matrix.Lerp = function (startValue, endValue, gradient) {
  5456. var result = Matrix.Zero();
  5457. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5458. return result;
  5459. };
  5460. /**
  5461. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5462. * @param startValue defines the start value
  5463. * @param endValue defines the end value
  5464. * @param gradient defines the gradient factor
  5465. * @param result defines the Matrix object where to store data
  5466. */
  5467. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5468. for (var index = 0; index < 16; index++) {
  5469. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5470. }
  5471. result._markAsUpdated();
  5472. };
  5473. /**
  5474. * Returns a new Matrix whose values are computed by :
  5475. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5476. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5477. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5478. */
  5479. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5480. var startScale = new Vector3(0, 0, 0);
  5481. var startRotation = new Quaternion();
  5482. var startTranslation = new Vector3(0, 0, 0);
  5483. startValue.decompose(startScale, startRotation, startTranslation);
  5484. var endScale = new Vector3(0, 0, 0);
  5485. var endRotation = new Quaternion();
  5486. var endTranslation = new Vector3(0, 0, 0);
  5487. endValue.decompose(endScale, endRotation, endTranslation);
  5488. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5489. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5490. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5491. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5492. };
  5493. /**
  5494. * 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".
  5495. * This methods works for a Left-Handed system.
  5496. */
  5497. Matrix.LookAtLH = function (eye, target, up) {
  5498. var result = Matrix.Zero();
  5499. Matrix.LookAtLHToRef(eye, target, up, result);
  5500. return result;
  5501. };
  5502. /**
  5503. * 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".
  5504. * This methods works for a Left-Handed system.
  5505. */
  5506. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5507. // Z axis
  5508. target.subtractToRef(eye, this._zAxis);
  5509. this._zAxis.normalize();
  5510. // X axis
  5511. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5512. if (this._xAxis.lengthSquared() === 0) {
  5513. this._xAxis.x = 1.0;
  5514. }
  5515. else {
  5516. this._xAxis.normalize();
  5517. }
  5518. // Y axis
  5519. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5520. this._yAxis.normalize();
  5521. // Eye angles
  5522. var ex = -Vector3.Dot(this._xAxis, eye);
  5523. var ey = -Vector3.Dot(this._yAxis, eye);
  5524. var ez = -Vector3.Dot(this._zAxis, eye);
  5525. 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);
  5526. };
  5527. /**
  5528. * 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".
  5529. * This methods works for a Right-Handed system.
  5530. */
  5531. Matrix.LookAtRH = function (eye, target, up) {
  5532. var result = Matrix.Zero();
  5533. Matrix.LookAtRHToRef(eye, target, up, result);
  5534. return result;
  5535. };
  5536. /**
  5537. * 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".
  5538. * This methods works for a Left-Handed system.
  5539. */
  5540. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5541. // Z axis
  5542. eye.subtractToRef(target, this._zAxis);
  5543. this._zAxis.normalize();
  5544. // X axis
  5545. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5546. if (this._xAxis.lengthSquared() === 0) {
  5547. this._xAxis.x = 1.0;
  5548. }
  5549. else {
  5550. this._xAxis.normalize();
  5551. }
  5552. // Y axis
  5553. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5554. this._yAxis.normalize();
  5555. // Eye angles
  5556. var ex = -Vector3.Dot(this._xAxis, eye);
  5557. var ey = -Vector3.Dot(this._yAxis, eye);
  5558. var ez = -Vector3.Dot(this._zAxis, eye);
  5559. 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);
  5560. };
  5561. /**
  5562. * 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.
  5563. */
  5564. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5565. var matrix = Matrix.Zero();
  5566. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5567. return matrix;
  5568. };
  5569. /**
  5570. * 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.
  5571. */
  5572. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5573. var n = znear;
  5574. var f = zfar;
  5575. var a = 2.0 / width;
  5576. var b = 2.0 / height;
  5577. var c = 2.0 / (f - n);
  5578. var d = -(f + n) / (f - n);
  5579. 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);
  5580. };
  5581. /**
  5582. * 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.
  5583. */
  5584. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5585. var matrix = Matrix.Zero();
  5586. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5587. return matrix;
  5588. };
  5589. /**
  5590. * 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.
  5591. */
  5592. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5593. var n = znear;
  5594. var f = zfar;
  5595. var a = 2.0 / (right - left);
  5596. var b = 2.0 / (top - bottom);
  5597. var c = 2.0 / (f - n);
  5598. var d = -(f + n) / (f - n);
  5599. var i0 = (left + right) / (left - right);
  5600. var i1 = (top + bottom) / (bottom - top);
  5601. 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);
  5602. };
  5603. /**
  5604. * 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.
  5605. */
  5606. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5607. var matrix = Matrix.Zero();
  5608. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5609. return matrix;
  5610. };
  5611. /**
  5612. * 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.
  5613. */
  5614. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5615. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5616. result.m[10] *= -1.0;
  5617. };
  5618. /**
  5619. * 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.
  5620. */
  5621. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5622. var matrix = Matrix.Zero();
  5623. var n = znear;
  5624. var f = zfar;
  5625. var a = 2.0 * n / width;
  5626. var b = 2.0 * n / height;
  5627. var c = (f + n) / (f - n);
  5628. var d = -2.0 * f * n / (f - n);
  5629. 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);
  5630. return matrix;
  5631. };
  5632. /**
  5633. * 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.
  5634. */
  5635. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5636. var matrix = Matrix.Zero();
  5637. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5638. return matrix;
  5639. };
  5640. /**
  5641. * 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.
  5642. */
  5643. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5644. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5645. var n = znear;
  5646. var f = zfar;
  5647. var t = 1.0 / (Math.tan(fov * 0.5));
  5648. var a = isVerticalFovFixed ? (t / aspect) : t;
  5649. var b = isVerticalFovFixed ? t : (t * aspect);
  5650. var c = (f + n) / (f - n);
  5651. var d = -2.0 * f * n / (f - n);
  5652. 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);
  5653. };
  5654. /**
  5655. * 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.
  5656. */
  5657. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5658. var matrix = Matrix.Zero();
  5659. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5660. return matrix;
  5661. };
  5662. /**
  5663. * 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.
  5664. */
  5665. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5666. //alternatively this could be expressed as:
  5667. // m = PerspectiveFovLHToRef
  5668. // m[10] *= -1.0;
  5669. // m[11] *= -1.0;
  5670. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5671. var n = znear;
  5672. var f = zfar;
  5673. var t = 1.0 / (Math.tan(fov * 0.5));
  5674. var a = isVerticalFovFixed ? (t / aspect) : t;
  5675. var b = isVerticalFovFixed ? t : (t * aspect);
  5676. var c = -(f + n) / (f - n);
  5677. var d = -2 * f * n / (f - n);
  5678. 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);
  5679. };
  5680. /**
  5681. * 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.
  5682. */
  5683. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5684. if (rightHanded === void 0) { rightHanded = false; }
  5685. var rightHandedFactor = rightHanded ? -1 : 1;
  5686. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5687. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5688. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5689. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5690. var xScale = 2.0 / (leftTan + rightTan);
  5691. var yScale = 2.0 / (upTan + downTan);
  5692. result.m[0] = xScale;
  5693. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5694. result.m[5] = yScale;
  5695. result.m[6] = result.m[7] = 0.0;
  5696. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5697. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5698. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5699. result.m[10] = -zfar / (znear - zfar);
  5700. result.m[11] = 1.0 * rightHandedFactor;
  5701. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5702. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5703. // result.m[14] = (znear * zfar) / (znear - zfar);
  5704. result._markAsUpdated();
  5705. };
  5706. /**
  5707. * Returns the final transformation matrix : world * view * projection * viewport
  5708. */
  5709. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5710. var cw = viewport.width;
  5711. var ch = viewport.height;
  5712. var cx = viewport.x;
  5713. var cy = viewport.y;
  5714. 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);
  5715. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5716. };
  5717. /**
  5718. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5719. */
  5720. Matrix.GetAsMatrix2x2 = function (matrix) {
  5721. return new Float32Array([
  5722. matrix.m[0], matrix.m[1],
  5723. matrix.m[4], matrix.m[5]
  5724. ]);
  5725. };
  5726. /**
  5727. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5728. */
  5729. Matrix.GetAsMatrix3x3 = function (matrix) {
  5730. return new Float32Array([
  5731. matrix.m[0], matrix.m[1], matrix.m[2],
  5732. matrix.m[4], matrix.m[5], matrix.m[6],
  5733. matrix.m[8], matrix.m[9], matrix.m[10]
  5734. ]);
  5735. };
  5736. /**
  5737. * Compute the transpose of the passed Matrix.
  5738. * Returns a new Matrix.
  5739. */
  5740. Matrix.Transpose = function (matrix) {
  5741. var result = new Matrix();
  5742. Matrix.TransposeToRef(matrix, result);
  5743. return result;
  5744. };
  5745. /**
  5746. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5747. */
  5748. Matrix.TransposeToRef = function (matrix, result) {
  5749. result.m[0] = matrix.m[0];
  5750. result.m[1] = matrix.m[4];
  5751. result.m[2] = matrix.m[8];
  5752. result.m[3] = matrix.m[12];
  5753. result.m[4] = matrix.m[1];
  5754. result.m[5] = matrix.m[5];
  5755. result.m[6] = matrix.m[9];
  5756. result.m[7] = matrix.m[13];
  5757. result.m[8] = matrix.m[2];
  5758. result.m[9] = matrix.m[6];
  5759. result.m[10] = matrix.m[10];
  5760. result.m[11] = matrix.m[14];
  5761. result.m[12] = matrix.m[3];
  5762. result.m[13] = matrix.m[7];
  5763. result.m[14] = matrix.m[11];
  5764. result.m[15] = matrix.m[15];
  5765. };
  5766. /**
  5767. * Returns a new Matrix as the reflection matrix across the passed plane.
  5768. */
  5769. Matrix.Reflection = function (plane) {
  5770. var matrix = new Matrix();
  5771. Matrix.ReflectionToRef(plane, matrix);
  5772. return matrix;
  5773. };
  5774. /**
  5775. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5776. */
  5777. Matrix.ReflectionToRef = function (plane, result) {
  5778. plane.normalize();
  5779. var x = plane.normal.x;
  5780. var y = plane.normal.y;
  5781. var z = plane.normal.z;
  5782. var temp = -2 * x;
  5783. var temp2 = -2 * y;
  5784. var temp3 = -2 * z;
  5785. result.m[0] = (temp * x) + 1;
  5786. result.m[1] = temp2 * x;
  5787. result.m[2] = temp3 * x;
  5788. result.m[3] = 0.0;
  5789. result.m[4] = temp * y;
  5790. result.m[5] = (temp2 * y) + 1;
  5791. result.m[6] = temp3 * y;
  5792. result.m[7] = 0.0;
  5793. result.m[8] = temp * z;
  5794. result.m[9] = temp2 * z;
  5795. result.m[10] = (temp3 * z) + 1;
  5796. result.m[11] = 0.0;
  5797. result.m[12] = temp * plane.d;
  5798. result.m[13] = temp2 * plane.d;
  5799. result.m[14] = temp3 * plane.d;
  5800. result.m[15] = 1.0;
  5801. result._markAsUpdated();
  5802. };
  5803. /**
  5804. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5805. */
  5806. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5807. result.m[0] = xaxis.x;
  5808. result.m[1] = xaxis.y;
  5809. result.m[2] = xaxis.z;
  5810. result.m[3] = 0.0;
  5811. result.m[4] = yaxis.x;
  5812. result.m[5] = yaxis.y;
  5813. result.m[6] = yaxis.z;
  5814. result.m[7] = 0.0;
  5815. result.m[8] = zaxis.x;
  5816. result.m[9] = zaxis.y;
  5817. result.m[10] = zaxis.z;
  5818. result.m[11] = 0.0;
  5819. result.m[12] = 0.0;
  5820. result.m[13] = 0.0;
  5821. result.m[14] = 0.0;
  5822. result.m[15] = 1.0;
  5823. result._markAsUpdated();
  5824. };
  5825. /**
  5826. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5827. */
  5828. Matrix.FromQuaternionToRef = function (quat, result) {
  5829. var xx = quat.x * quat.x;
  5830. var yy = quat.y * quat.y;
  5831. var zz = quat.z * quat.z;
  5832. var xy = quat.x * quat.y;
  5833. var zw = quat.z * quat.w;
  5834. var zx = quat.z * quat.x;
  5835. var yw = quat.y * quat.w;
  5836. var yz = quat.y * quat.z;
  5837. var xw = quat.x * quat.w;
  5838. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5839. result.m[1] = 2.0 * (xy + zw);
  5840. result.m[2] = 2.0 * (zx - yw);
  5841. result.m[3] = 0.0;
  5842. result.m[4] = 2.0 * (xy - zw);
  5843. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5844. result.m[6] = 2.0 * (yz + xw);
  5845. result.m[7] = 0.0;
  5846. result.m[8] = 2.0 * (zx + yw);
  5847. result.m[9] = 2.0 * (yz - xw);
  5848. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5849. result.m[11] = 0.0;
  5850. result.m[12] = 0.0;
  5851. result.m[13] = 0.0;
  5852. result.m[14] = 0.0;
  5853. result.m[15] = 1.0;
  5854. result._markAsUpdated();
  5855. };
  5856. Matrix._tempQuaternion = new Quaternion();
  5857. Matrix._xAxis = Vector3.Zero();
  5858. Matrix._yAxis = Vector3.Zero();
  5859. Matrix._zAxis = Vector3.Zero();
  5860. Matrix._updateFlagSeed = 0;
  5861. Matrix._identityReadOnly = Matrix.Identity();
  5862. return Matrix;
  5863. }());
  5864. BABYLON.Matrix = Matrix;
  5865. var Plane = /** @class */ (function () {
  5866. /**
  5867. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5868. */
  5869. function Plane(a, b, c, d) {
  5870. this.normal = new Vector3(a, b, c);
  5871. this.d = d;
  5872. }
  5873. /**
  5874. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5875. */
  5876. Plane.prototype.asArray = function () {
  5877. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5878. };
  5879. // Methods
  5880. /**
  5881. * Returns a new plane copied from the current Plane.
  5882. */
  5883. Plane.prototype.clone = function () {
  5884. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5885. };
  5886. /**
  5887. * Returns the string "Plane".
  5888. */
  5889. Plane.prototype.getClassName = function () {
  5890. return "Plane";
  5891. };
  5892. /**
  5893. * Returns the Plane hash code.
  5894. */
  5895. Plane.prototype.getHashCode = function () {
  5896. var hash = this.normal.getHashCode();
  5897. hash = (hash * 397) ^ (this.d || 0);
  5898. return hash;
  5899. };
  5900. /**
  5901. * Normalize the current Plane in place.
  5902. * Returns the updated Plane.
  5903. */
  5904. Plane.prototype.normalize = function () {
  5905. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5906. var magnitude = 0.0;
  5907. if (norm !== 0) {
  5908. magnitude = 1.0 / norm;
  5909. }
  5910. this.normal.x *= magnitude;
  5911. this.normal.y *= magnitude;
  5912. this.normal.z *= magnitude;
  5913. this.d *= magnitude;
  5914. return this;
  5915. };
  5916. /**
  5917. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5918. */
  5919. Plane.prototype.transform = function (transformation) {
  5920. var transposedMatrix = Matrix.Transpose(transformation);
  5921. var x = this.normal.x;
  5922. var y = this.normal.y;
  5923. var z = this.normal.z;
  5924. var d = this.d;
  5925. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5926. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5927. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5928. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5929. return new Plane(normalX, normalY, normalZ, finalD);
  5930. };
  5931. /**
  5932. * Returns the dot product (float) of the point coordinates and the plane normal.
  5933. */
  5934. Plane.prototype.dotCoordinate = function (point) {
  5935. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5936. };
  5937. /**
  5938. * Updates the current Plane from the plane defined by the three passed points.
  5939. * Returns the updated Plane.
  5940. */
  5941. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5942. var x1 = point2.x - point1.x;
  5943. var y1 = point2.y - point1.y;
  5944. var z1 = point2.z - point1.z;
  5945. var x2 = point3.x - point1.x;
  5946. var y2 = point3.y - point1.y;
  5947. var z2 = point3.z - point1.z;
  5948. var yz = (y1 * z2) - (z1 * y2);
  5949. var xz = (z1 * x2) - (x1 * z2);
  5950. var xy = (x1 * y2) - (y1 * x2);
  5951. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5952. var invPyth;
  5953. if (pyth !== 0) {
  5954. invPyth = 1.0 / pyth;
  5955. }
  5956. else {
  5957. invPyth = 0.0;
  5958. }
  5959. this.normal.x = yz * invPyth;
  5960. this.normal.y = xz * invPyth;
  5961. this.normal.z = xy * invPyth;
  5962. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5963. return this;
  5964. };
  5965. /**
  5966. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5967. */
  5968. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5969. var dot = Vector3.Dot(this.normal, direction);
  5970. return (dot <= epsilon);
  5971. };
  5972. /**
  5973. * Returns the signed distance (float) from the passed point to the Plane.
  5974. */
  5975. Plane.prototype.signedDistanceTo = function (point) {
  5976. return Vector3.Dot(point, this.normal) + this.d;
  5977. };
  5978. // Statics
  5979. /**
  5980. * Returns a new Plane from the passed array.
  5981. */
  5982. Plane.FromArray = function (array) {
  5983. return new Plane(array[0], array[1], array[2], array[3]);
  5984. };
  5985. /**
  5986. * Returns a new Plane defined by the three passed points.
  5987. */
  5988. Plane.FromPoints = function (point1, point2, point3) {
  5989. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5990. result.copyFromPoints(point1, point2, point3);
  5991. return result;
  5992. };
  5993. /**
  5994. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5995. * Note : the vector "normal" is updated because normalized.
  5996. */
  5997. Plane.FromPositionAndNormal = function (origin, normal) {
  5998. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5999. normal.normalize();
  6000. result.normal = normal;
  6001. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6002. return result;
  6003. };
  6004. /**
  6005. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6006. */
  6007. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6008. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6009. return Vector3.Dot(point, normal) + d;
  6010. };
  6011. return Plane;
  6012. }());
  6013. BABYLON.Plane = Plane;
  6014. var Viewport = /** @class */ (function () {
  6015. /**
  6016. * Creates a Viewport object located at (x, y) and sized (width, height).
  6017. */
  6018. function Viewport(x, y, width, height) {
  6019. this.x = x;
  6020. this.y = y;
  6021. this.width = width;
  6022. this.height = height;
  6023. }
  6024. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6025. if (renderWidthOrEngine.getRenderWidth) {
  6026. var engine = renderWidthOrEngine;
  6027. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6028. }
  6029. var renderWidth = renderWidthOrEngine;
  6030. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6031. };
  6032. /**
  6033. * Returns a new Viewport copied from the current one.
  6034. */
  6035. Viewport.prototype.clone = function () {
  6036. return new Viewport(this.x, this.y, this.width, this.height);
  6037. };
  6038. return Viewport;
  6039. }());
  6040. BABYLON.Viewport = Viewport;
  6041. var Frustum = /** @class */ (function () {
  6042. function Frustum() {
  6043. }
  6044. /**
  6045. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6046. */
  6047. Frustum.GetPlanes = function (transform) {
  6048. var frustumPlanes = [];
  6049. for (var index = 0; index < 6; index++) {
  6050. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6051. }
  6052. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6053. return frustumPlanes;
  6054. };
  6055. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6056. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6057. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6058. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6059. frustumPlane.d = transform.m[15] + transform.m[14];
  6060. frustumPlane.normalize();
  6061. };
  6062. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6063. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6064. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6065. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6066. frustumPlane.d = transform.m[15] - transform.m[14];
  6067. frustumPlane.normalize();
  6068. };
  6069. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6070. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6071. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6072. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6073. frustumPlane.d = transform.m[15] + transform.m[12];
  6074. frustumPlane.normalize();
  6075. };
  6076. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6077. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6078. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6079. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6080. frustumPlane.d = transform.m[15] - transform.m[12];
  6081. frustumPlane.normalize();
  6082. };
  6083. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6084. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6085. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6086. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6087. frustumPlane.d = transform.m[15] - transform.m[13];
  6088. frustumPlane.normalize();
  6089. };
  6090. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6091. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6092. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6093. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6094. frustumPlane.d = transform.m[15] + transform.m[13];
  6095. frustumPlane.normalize();
  6096. };
  6097. /**
  6098. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6099. */
  6100. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6101. // Near
  6102. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6103. // Far
  6104. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6105. // Left
  6106. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6107. // Right
  6108. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6109. // Top
  6110. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6111. // Bottom
  6112. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6113. };
  6114. return Frustum;
  6115. }());
  6116. BABYLON.Frustum = Frustum;
  6117. var Space;
  6118. (function (Space) {
  6119. Space[Space["LOCAL"] = 0] = "LOCAL";
  6120. Space[Space["WORLD"] = 1] = "WORLD";
  6121. Space[Space["BONE"] = 2] = "BONE";
  6122. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6123. var Axis = /** @class */ (function () {
  6124. function Axis() {
  6125. }
  6126. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6127. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6128. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6129. return Axis;
  6130. }());
  6131. BABYLON.Axis = Axis;
  6132. ;
  6133. var BezierCurve = /** @class */ (function () {
  6134. function BezierCurve() {
  6135. }
  6136. /**
  6137. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6138. */
  6139. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6140. // Extract X (which is equal to time here)
  6141. var f0 = 1 - 3 * x2 + 3 * x1;
  6142. var f1 = 3 * x2 - 6 * x1;
  6143. var f2 = 3 * x1;
  6144. var refinedT = t;
  6145. for (var i = 0; i < 5; i++) {
  6146. var refinedT2 = refinedT * refinedT;
  6147. var refinedT3 = refinedT2 * refinedT;
  6148. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6149. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6150. refinedT -= (x - t) * slope;
  6151. refinedT = Math.min(1, Math.max(0, refinedT));
  6152. }
  6153. // Resolve cubic bezier for the given x
  6154. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6155. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6156. Math.pow(refinedT, 3);
  6157. };
  6158. return BezierCurve;
  6159. }());
  6160. BABYLON.BezierCurve = BezierCurve;
  6161. var Orientation;
  6162. (function (Orientation) {
  6163. Orientation[Orientation["CW"] = 0] = "CW";
  6164. Orientation[Orientation["CCW"] = 1] = "CCW";
  6165. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6166. var Angle = /** @class */ (function () {
  6167. /**
  6168. * Creates an Angle object of "radians" radians (float).
  6169. */
  6170. function Angle(radians) {
  6171. var _this = this;
  6172. /**
  6173. * Returns the Angle value in degrees (float).
  6174. */
  6175. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6176. /**
  6177. * Returns the Angle value in radians (float).
  6178. */
  6179. this.radians = function () { return _this._radians; };
  6180. this._radians = radians;
  6181. if (this._radians < 0.0)
  6182. this._radians += (2.0 * Math.PI);
  6183. }
  6184. /**
  6185. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6186. */
  6187. Angle.BetweenTwoPoints = function (a, b) {
  6188. var delta = b.subtract(a);
  6189. var theta = Math.atan2(delta.y, delta.x);
  6190. return new Angle(theta);
  6191. };
  6192. /**
  6193. * Returns a new Angle object from the passed float in radians.
  6194. */
  6195. Angle.FromRadians = function (radians) {
  6196. return new Angle(radians);
  6197. };
  6198. /**
  6199. * Returns a new Angle object from the passed float in degrees.
  6200. */
  6201. Angle.FromDegrees = function (degrees) {
  6202. return new Angle(degrees * Math.PI / 180.0);
  6203. };
  6204. return Angle;
  6205. }());
  6206. BABYLON.Angle = Angle;
  6207. var Arc2 = /** @class */ (function () {
  6208. /**
  6209. * Creates an Arc object from the three passed points : start, middle and end.
  6210. */
  6211. function Arc2(startPoint, midPoint, endPoint) {
  6212. this.startPoint = startPoint;
  6213. this.midPoint = midPoint;
  6214. this.endPoint = endPoint;
  6215. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6216. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6217. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6218. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6219. 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);
  6220. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6221. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6222. var a1 = this.startAngle.degrees();
  6223. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6224. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6225. // angles correction
  6226. if (a2 - a1 > +180.0)
  6227. a2 -= 360.0;
  6228. if (a2 - a1 < -180.0)
  6229. a2 += 360.0;
  6230. if (a3 - a2 > +180.0)
  6231. a3 -= 360.0;
  6232. if (a3 - a2 < -180.0)
  6233. a3 += 360.0;
  6234. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6235. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6236. }
  6237. return Arc2;
  6238. }());
  6239. BABYLON.Arc2 = Arc2;
  6240. var Path2 = /** @class */ (function () {
  6241. /**
  6242. * Creates a Path2 object from the starting 2D coordinates x and y.
  6243. */
  6244. function Path2(x, y) {
  6245. this._points = new Array();
  6246. this._length = 0.0;
  6247. this.closed = false;
  6248. this._points.push(new Vector2(x, y));
  6249. }
  6250. /**
  6251. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6252. * Returns the updated Path2.
  6253. */
  6254. Path2.prototype.addLineTo = function (x, y) {
  6255. if (this.closed) {
  6256. return this;
  6257. }
  6258. var newPoint = new Vector2(x, y);
  6259. var previousPoint = this._points[this._points.length - 1];
  6260. this._points.push(newPoint);
  6261. this._length += newPoint.subtract(previousPoint).length();
  6262. return this;
  6263. };
  6264. /**
  6265. * 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.
  6266. * Returns the updated Path2.
  6267. */
  6268. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6269. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6270. if (this.closed) {
  6271. return this;
  6272. }
  6273. var startPoint = this._points[this._points.length - 1];
  6274. var midPoint = new Vector2(midX, midY);
  6275. var endPoint = new Vector2(endX, endY);
  6276. var arc = new Arc2(startPoint, midPoint, endPoint);
  6277. var increment = arc.angle.radians() / numberOfSegments;
  6278. if (arc.orientation === Orientation.CW)
  6279. increment *= -1;
  6280. var currentAngle = arc.startAngle.radians() + increment;
  6281. for (var i = 0; i < numberOfSegments; i++) {
  6282. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6283. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6284. this.addLineTo(x, y);
  6285. currentAngle += increment;
  6286. }
  6287. return this;
  6288. };
  6289. /**
  6290. * Closes the Path2.
  6291. * Returns the Path2.
  6292. */
  6293. Path2.prototype.close = function () {
  6294. this.closed = true;
  6295. return this;
  6296. };
  6297. /**
  6298. * Returns the Path2 total length (float).
  6299. */
  6300. Path2.prototype.length = function () {
  6301. var result = this._length;
  6302. if (!this.closed) {
  6303. var lastPoint = this._points[this._points.length - 1];
  6304. var firstPoint = this._points[0];
  6305. result += (firstPoint.subtract(lastPoint).length());
  6306. }
  6307. return result;
  6308. };
  6309. /**
  6310. * Returns the Path2 internal array of points.
  6311. */
  6312. Path2.prototype.getPoints = function () {
  6313. return this._points;
  6314. };
  6315. /**
  6316. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6317. */
  6318. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6319. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6320. return Vector2.Zero();
  6321. }
  6322. var lengthPosition = normalizedLengthPosition * this.length();
  6323. var previousOffset = 0;
  6324. for (var i = 0; i < this._points.length; i++) {
  6325. var j = (i + 1) % this._points.length;
  6326. var a = this._points[i];
  6327. var b = this._points[j];
  6328. var bToA = b.subtract(a);
  6329. var nextOffset = (bToA.length() + previousOffset);
  6330. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6331. var dir = bToA.normalize();
  6332. var localOffset = lengthPosition - previousOffset;
  6333. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6334. }
  6335. previousOffset = nextOffset;
  6336. }
  6337. return Vector2.Zero();
  6338. };
  6339. /**
  6340. * Returns a new Path2 starting at the coordinates (x, y).
  6341. */
  6342. Path2.StartingAt = function (x, y) {
  6343. return new Path2(x, y);
  6344. };
  6345. return Path2;
  6346. }());
  6347. BABYLON.Path2 = Path2;
  6348. var Path3D = /** @class */ (function () {
  6349. /**
  6350. * new Path3D(path, normal, raw)
  6351. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6352. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6353. * path : an array of Vector3, the curve axis of the Path3D
  6354. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6355. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6356. */
  6357. function Path3D(path, firstNormal, raw) {
  6358. if (firstNormal === void 0) { firstNormal = null; }
  6359. this.path = path;
  6360. this._curve = new Array();
  6361. this._distances = new Array();
  6362. this._tangents = new Array();
  6363. this._normals = new Array();
  6364. this._binormals = new Array();
  6365. for (var p = 0; p < path.length; p++) {
  6366. this._curve[p] = path[p].clone(); // hard copy
  6367. }
  6368. this._raw = raw || false;
  6369. this._compute(firstNormal);
  6370. }
  6371. /**
  6372. * Returns the Path3D array of successive Vector3 designing its curve.
  6373. */
  6374. Path3D.prototype.getCurve = function () {
  6375. return this._curve;
  6376. };
  6377. /**
  6378. * Returns an array populated with tangent vectors on each Path3D curve point.
  6379. */
  6380. Path3D.prototype.getTangents = function () {
  6381. return this._tangents;
  6382. };
  6383. /**
  6384. * Returns an array populated with normal vectors on each Path3D curve point.
  6385. */
  6386. Path3D.prototype.getNormals = function () {
  6387. return this._normals;
  6388. };
  6389. /**
  6390. * Returns an array populated with binormal vectors on each Path3D curve point.
  6391. */
  6392. Path3D.prototype.getBinormals = function () {
  6393. return this._binormals;
  6394. };
  6395. /**
  6396. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6397. */
  6398. Path3D.prototype.getDistances = function () {
  6399. return this._distances;
  6400. };
  6401. /**
  6402. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6403. * Returns the same object updated.
  6404. */
  6405. Path3D.prototype.update = function (path, firstNormal) {
  6406. if (firstNormal === void 0) { firstNormal = null; }
  6407. for (var p = 0; p < path.length; p++) {
  6408. this._curve[p].x = path[p].x;
  6409. this._curve[p].y = path[p].y;
  6410. this._curve[p].z = path[p].z;
  6411. }
  6412. this._compute(firstNormal);
  6413. return this;
  6414. };
  6415. // private function compute() : computes tangents, normals and binormals
  6416. Path3D.prototype._compute = function (firstNormal) {
  6417. var l = this._curve.length;
  6418. // first and last tangents
  6419. this._tangents[0] = this._getFirstNonNullVector(0);
  6420. if (!this._raw) {
  6421. this._tangents[0].normalize();
  6422. }
  6423. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6424. if (!this._raw) {
  6425. this._tangents[l - 1].normalize();
  6426. }
  6427. // normals and binormals at first point : arbitrary vector with _normalVector()
  6428. var tg0 = this._tangents[0];
  6429. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6430. this._normals[0] = pp0;
  6431. if (!this._raw) {
  6432. this._normals[0].normalize();
  6433. }
  6434. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6435. if (!this._raw) {
  6436. this._binormals[0].normalize();
  6437. }
  6438. this._distances[0] = 0.0;
  6439. // normals and binormals : next points
  6440. var prev; // previous vector (segment)
  6441. var cur; // current vector (segment)
  6442. var curTang; // current tangent
  6443. // previous normal
  6444. var prevBinor; // previous binormal
  6445. for (var i = 1; i < l; i++) {
  6446. // tangents
  6447. prev = this._getLastNonNullVector(i);
  6448. if (i < l - 1) {
  6449. cur = this._getFirstNonNullVector(i);
  6450. this._tangents[i] = prev.add(cur);
  6451. this._tangents[i].normalize();
  6452. }
  6453. this._distances[i] = this._distances[i - 1] + prev.length();
  6454. // normals and binormals
  6455. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6456. curTang = this._tangents[i];
  6457. prevBinor = this._binormals[i - 1];
  6458. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6459. if (!this._raw) {
  6460. this._normals[i].normalize();
  6461. }
  6462. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6463. if (!this._raw) {
  6464. this._binormals[i].normalize();
  6465. }
  6466. }
  6467. };
  6468. // private function getFirstNonNullVector(index)
  6469. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6470. Path3D.prototype._getFirstNonNullVector = function (index) {
  6471. var i = 1;
  6472. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6473. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6474. i++;
  6475. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6476. }
  6477. return nNVector;
  6478. };
  6479. // private function getLastNonNullVector(index)
  6480. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6481. Path3D.prototype._getLastNonNullVector = function (index) {
  6482. var i = 1;
  6483. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6484. while (nLVector.length() === 0 && index > i + 1) {
  6485. i++;
  6486. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6487. }
  6488. return nLVector;
  6489. };
  6490. // private function normalVector(v0, vt, va) :
  6491. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6492. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6493. Path3D.prototype._normalVector = function (v0, vt, va) {
  6494. var normal0;
  6495. var tgl = vt.length();
  6496. if (tgl === 0.0) {
  6497. tgl = 1.0;
  6498. }
  6499. if (va === undefined || va === null) {
  6500. var point;
  6501. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6502. point = new Vector3(0.0, -1.0, 0.0);
  6503. }
  6504. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6505. point = new Vector3(1.0, 0.0, 0.0);
  6506. }
  6507. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6508. point = new Vector3(0.0, 0.0, 1.0);
  6509. }
  6510. else {
  6511. point = Vector3.Zero();
  6512. }
  6513. normal0 = Vector3.Cross(vt, point);
  6514. }
  6515. else {
  6516. normal0 = Vector3.Cross(vt, va);
  6517. Vector3.CrossToRef(normal0, vt, normal0);
  6518. }
  6519. normal0.normalize();
  6520. return normal0;
  6521. };
  6522. return Path3D;
  6523. }());
  6524. BABYLON.Path3D = Path3D;
  6525. var Curve3 = /** @class */ (function () {
  6526. /**
  6527. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6528. * A Curve3 is designed from a series of successive Vector3.
  6529. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6530. */
  6531. function Curve3(points) {
  6532. this._length = 0.0;
  6533. this._points = points;
  6534. this._length = this._computeLength(points);
  6535. }
  6536. /**
  6537. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6538. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6539. * @param v1 (Vector3) the control point
  6540. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6541. * @param nbPoints (integer) the wanted number of points in the curve
  6542. */
  6543. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6544. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6545. var bez = new Array();
  6546. var equation = function (t, val0, val1, val2) {
  6547. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6548. return res;
  6549. };
  6550. for (var i = 0; i <= nbPoints; i++) {
  6551. 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)));
  6552. }
  6553. return new Curve3(bez);
  6554. };
  6555. /**
  6556. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6557. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6558. * @param v1 (Vector3) the first control point
  6559. * @param v2 (Vector3) the second control point
  6560. * @param v3 (Vector3) the end point of the Cubic Bezier
  6561. * @param nbPoints (integer) the wanted number of points in the curve
  6562. */
  6563. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6564. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6565. var bez = new Array();
  6566. var equation = function (t, val0, val1, val2, val3) {
  6567. 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;
  6568. return res;
  6569. };
  6570. for (var i = 0; i <= nbPoints; i++) {
  6571. 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)));
  6572. }
  6573. return new Curve3(bez);
  6574. };
  6575. /**
  6576. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6577. * @param p1 (Vector3) the origin point of the Hermite Spline
  6578. * @param t1 (Vector3) the tangent vector at the origin point
  6579. * @param p2 (Vector3) the end point of the Hermite Spline
  6580. * @param t2 (Vector3) the tangent vector at the end point
  6581. * @param nbPoints (integer) the wanted number of points in the curve
  6582. */
  6583. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6584. var hermite = new Array();
  6585. var step = 1.0 / nbPoints;
  6586. for (var i = 0; i <= nbPoints; i++) {
  6587. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6588. }
  6589. return new Curve3(hermite);
  6590. };
  6591. /**
  6592. * Returns a Curve3 object along a CatmullRom Spline curve :
  6593. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6594. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6595. */
  6596. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6597. var totalPoints = new Array();
  6598. totalPoints.push(points[0].clone());
  6599. Array.prototype.push.apply(totalPoints, points);
  6600. totalPoints.push(points[points.length - 1].clone());
  6601. var catmullRom = new Array();
  6602. var step = 1.0 / nbPoints;
  6603. var amount = 0.0;
  6604. for (var i = 0; i < totalPoints.length - 3; i++) {
  6605. amount = 0;
  6606. for (var c = 0; c < nbPoints; c++) {
  6607. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6608. amount += step;
  6609. }
  6610. }
  6611. i--;
  6612. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6613. return new Curve3(catmullRom);
  6614. };
  6615. /**
  6616. * Returns the Curve3 stored array of successive Vector3
  6617. */
  6618. Curve3.prototype.getPoints = function () {
  6619. return this._points;
  6620. };
  6621. /**
  6622. * Returns the computed length (float) of the curve.
  6623. */
  6624. Curve3.prototype.length = function () {
  6625. return this._length;
  6626. };
  6627. /**
  6628. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6629. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6630. * curveA and curveB keep unchanged.
  6631. */
  6632. Curve3.prototype.continue = function (curve) {
  6633. var lastPoint = this._points[this._points.length - 1];
  6634. var continuedPoints = this._points.slice();
  6635. var curvePoints = curve.getPoints();
  6636. for (var i = 1; i < curvePoints.length; i++) {
  6637. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6638. }
  6639. var continuedCurve = new Curve3(continuedPoints);
  6640. return continuedCurve;
  6641. };
  6642. Curve3.prototype._computeLength = function (path) {
  6643. var l = 0;
  6644. for (var i = 1; i < path.length; i++) {
  6645. l += (path[i].subtract(path[i - 1])).length();
  6646. }
  6647. return l;
  6648. };
  6649. return Curve3;
  6650. }());
  6651. BABYLON.Curve3 = Curve3;
  6652. // Vertex formats
  6653. var PositionNormalVertex = /** @class */ (function () {
  6654. function PositionNormalVertex(position, normal) {
  6655. if (position === void 0) { position = Vector3.Zero(); }
  6656. if (normal === void 0) { normal = Vector3.Up(); }
  6657. this.position = position;
  6658. this.normal = normal;
  6659. }
  6660. PositionNormalVertex.prototype.clone = function () {
  6661. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6662. };
  6663. return PositionNormalVertex;
  6664. }());
  6665. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6666. var PositionNormalTextureVertex = /** @class */ (function () {
  6667. function PositionNormalTextureVertex(position, normal, uv) {
  6668. if (position === void 0) { position = Vector3.Zero(); }
  6669. if (normal === void 0) { normal = Vector3.Up(); }
  6670. if (uv === void 0) { uv = Vector2.Zero(); }
  6671. this.position = position;
  6672. this.normal = normal;
  6673. this.uv = uv;
  6674. }
  6675. PositionNormalTextureVertex.prototype.clone = function () {
  6676. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6677. };
  6678. return PositionNormalTextureVertex;
  6679. }());
  6680. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6681. // Temporary pre-allocated objects for engine internal use
  6682. // usage in any internal function :
  6683. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6684. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6685. var Tmp = /** @class */ (function () {
  6686. function Tmp() {
  6687. }
  6688. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6689. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6690. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6691. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6692. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6693. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6694. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6695. Matrix.Zero(), Matrix.Zero(),
  6696. Matrix.Zero(), Matrix.Zero(),
  6697. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6698. return Tmp;
  6699. }());
  6700. BABYLON.Tmp = Tmp;
  6701. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6702. var MathTmp = /** @class */ (function () {
  6703. function MathTmp() {
  6704. }
  6705. MathTmp.Vector3 = [Vector3.Zero()];
  6706. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6707. MathTmp.Quaternion = [Quaternion.Zero()];
  6708. return MathTmp;
  6709. }());
  6710. })(BABYLON || (BABYLON = {}));
  6711. //# sourceMappingURL=babylon.math.js.map
  6712. var BABYLON;
  6713. (function (BABYLON) {
  6714. var Scalar = /** @class */ (function () {
  6715. function Scalar() {
  6716. }
  6717. /**
  6718. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6719. */
  6720. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6721. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6722. var num = a - b;
  6723. return -epsilon <= num && num <= epsilon;
  6724. };
  6725. /**
  6726. * Returns a string : the upper case translation of the number i to hexadecimal.
  6727. */
  6728. Scalar.ToHex = function (i) {
  6729. var str = i.toString(16);
  6730. if (i <= 15) {
  6731. return ("0" + str).toUpperCase();
  6732. }
  6733. return str.toUpperCase();
  6734. };
  6735. /**
  6736. * Returns -1 if value is negative and +1 is value is positive.
  6737. * Returns the value itself if it's equal to zero.
  6738. */
  6739. Scalar.Sign = function (value) {
  6740. value = +value; // convert to a number
  6741. if (value === 0 || isNaN(value))
  6742. return value;
  6743. return value > 0 ? 1 : -1;
  6744. };
  6745. /**
  6746. * Returns the value itself if it's between min and max.
  6747. * Returns min if the value is lower than min.
  6748. * Returns max if the value is greater than max.
  6749. */
  6750. Scalar.Clamp = function (value, min, max) {
  6751. if (min === void 0) { min = 0; }
  6752. if (max === void 0) { max = 1; }
  6753. return Math.min(max, Math.max(min, value));
  6754. };
  6755. /**
  6756. * Returns the log2 of value.
  6757. */
  6758. Scalar.Log2 = function (value) {
  6759. return Math.log(value) * Math.LOG2E;
  6760. };
  6761. /**
  6762. * Loops the value, so that it is never larger than length and never smaller than 0.
  6763. *
  6764. * This is similar to the modulo operator but it works with floating point numbers.
  6765. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6766. * With t = 5 and length = 2.5, the result would be 0.0.
  6767. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6768. */
  6769. Scalar.Repeat = function (value, length) {
  6770. return value - Math.floor(value / length) * length;
  6771. };
  6772. /**
  6773. * Normalize the value between 0.0 and 1.0 using min and max values
  6774. */
  6775. Scalar.Normalize = function (value, min, max) {
  6776. return (value - min) / (max - min);
  6777. };
  6778. /**
  6779. * Denormalize the value from 0.0 and 1.0 using min and max values
  6780. */
  6781. Scalar.Denormalize = function (normalized, min, max) {
  6782. return (normalized * (max - min) + min);
  6783. };
  6784. /**
  6785. * Calculates the shortest difference between two given angles given in degrees.
  6786. */
  6787. Scalar.DeltaAngle = function (current, target) {
  6788. var num = Scalar.Repeat(target - current, 360.0);
  6789. if (num > 180.0) {
  6790. num -= 360.0;
  6791. }
  6792. return num;
  6793. };
  6794. /**
  6795. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6796. *
  6797. * The returned value will move back and forth between 0 and length
  6798. */
  6799. Scalar.PingPong = function (tx, length) {
  6800. var t = Scalar.Repeat(tx, length * 2.0);
  6801. return length - Math.abs(t - length);
  6802. };
  6803. /**
  6804. * Interpolates between min and max with smoothing at the limits.
  6805. *
  6806. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6807. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6808. */
  6809. Scalar.SmoothStep = function (from, to, tx) {
  6810. var t = Scalar.Clamp(tx);
  6811. t = -2.0 * t * t * t + 3.0 * t * t;
  6812. return to * t + from * (1.0 - t);
  6813. };
  6814. /**
  6815. * Moves a value current towards target.
  6816. *
  6817. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6818. * Negative values of maxDelta pushes the value away from target.
  6819. */
  6820. Scalar.MoveTowards = function (current, target, maxDelta) {
  6821. var result = 0;
  6822. if (Math.abs(target - current) <= maxDelta) {
  6823. result = target;
  6824. }
  6825. else {
  6826. result = current + Scalar.Sign(target - current) * maxDelta;
  6827. }
  6828. return result;
  6829. };
  6830. /**
  6831. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6832. *
  6833. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6834. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6835. */
  6836. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6837. var num = Scalar.DeltaAngle(current, target);
  6838. var result = 0;
  6839. if (-maxDelta < num && num < maxDelta) {
  6840. result = target;
  6841. }
  6842. else {
  6843. target = current + num;
  6844. result = Scalar.MoveTowards(current, target, maxDelta);
  6845. }
  6846. return result;
  6847. };
  6848. /**
  6849. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6850. */
  6851. Scalar.Lerp = function (start, end, amount) {
  6852. return start + ((end - start) * amount);
  6853. };
  6854. /**
  6855. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6856. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6857. */
  6858. Scalar.LerpAngle = function (start, end, amount) {
  6859. var num = Scalar.Repeat(end - start, 360.0);
  6860. if (num > 180.0) {
  6861. num -= 360.0;
  6862. }
  6863. return start + num * Scalar.Clamp(amount);
  6864. };
  6865. /**
  6866. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6867. */
  6868. Scalar.InverseLerp = function (a, b, value) {
  6869. var result = 0;
  6870. if (a != b) {
  6871. result = Scalar.Clamp((value - a) / (b - a));
  6872. }
  6873. else {
  6874. result = 0.0;
  6875. }
  6876. return result;
  6877. };
  6878. /**
  6879. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6880. */
  6881. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6882. var squared = amount * amount;
  6883. var cubed = amount * squared;
  6884. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6885. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6886. var part3 = (cubed - (2.0 * squared)) + amount;
  6887. var part4 = cubed - squared;
  6888. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6889. };
  6890. /**
  6891. * Returns a random float number between and min and max values
  6892. */
  6893. Scalar.RandomRange = function (min, max) {
  6894. if (min === max)
  6895. return min;
  6896. return ((Math.random() * (max - min)) + min);
  6897. };
  6898. /**
  6899. * This function returns percentage of a number in a given range.
  6900. *
  6901. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6902. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6903. */
  6904. Scalar.RangeToPercent = function (number, min, max) {
  6905. return ((number - min) / (max - min));
  6906. };
  6907. /**
  6908. * This function returns number that corresponds to the percentage in a given range.
  6909. *
  6910. * PercentToRange(0.34,0,100) will return 34.
  6911. */
  6912. Scalar.PercentToRange = function (percent, min, max) {
  6913. return ((max - min) * percent + min);
  6914. };
  6915. /**
  6916. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6917. * @param angle The angle to normalize in radian.
  6918. * @return The converted angle.
  6919. */
  6920. Scalar.NormalizeRadians = function (angle) {
  6921. // More precise but slower version kept for reference.
  6922. // angle = angle % Tools.TwoPi;
  6923. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6924. //if (angle > Math.PI) {
  6925. // angle -= Tools.TwoPi;
  6926. //}
  6927. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6928. return angle;
  6929. };
  6930. /**
  6931. * Two pi constants convenient for computation.
  6932. */
  6933. Scalar.TwoPi = Math.PI * 2;
  6934. return Scalar;
  6935. }());
  6936. BABYLON.Scalar = Scalar;
  6937. })(BABYLON || (BABYLON = {}));
  6938. //# sourceMappingURL=babylon.math.scalar.js.map
  6939. //# sourceMappingURL=babylon.mixins.js.map
  6940. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6941. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6942. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6943. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6944. //# sourceMappingURL=babylon.webgl2.js.map
  6945. var BABYLON;
  6946. (function (BABYLON) {
  6947. var __decoratorInitialStore = {};
  6948. var __mergedStore = {};
  6949. var _copySource = function (creationFunction, source, instanciate) {
  6950. var destination = creationFunction();
  6951. // Tags
  6952. if (BABYLON.Tags) {
  6953. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6954. }
  6955. var classStore = getMergedStore(destination);
  6956. // Properties
  6957. for (var property in classStore) {
  6958. var propertyDescriptor = classStore[property];
  6959. var sourceProperty = source[property];
  6960. var propertyType = propertyDescriptor.type;
  6961. if (sourceProperty !== undefined && sourceProperty !== null) {
  6962. switch (propertyType) {
  6963. case 0: // Value
  6964. case 6:// Mesh reference
  6965. destination[property] = sourceProperty;
  6966. break;
  6967. case 1:// Texture
  6968. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6969. break;
  6970. case 2: // Color3
  6971. case 3: // FresnelParameters
  6972. case 4: // Vector2
  6973. case 5: // Vector3
  6974. case 7: // Color Curves
  6975. case 10:// Quaternion
  6976. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6977. break;
  6978. }
  6979. }
  6980. }
  6981. return destination;
  6982. };
  6983. function getDirectStore(target) {
  6984. var classKey = target.getClassName();
  6985. if (!__decoratorInitialStore[classKey]) {
  6986. __decoratorInitialStore[classKey] = {};
  6987. }
  6988. return __decoratorInitialStore[classKey];
  6989. }
  6990. /**
  6991. * Return the list of properties flagged as serializable
  6992. * @param target: host object
  6993. */
  6994. function getMergedStore(target) {
  6995. var classKey = target.getClassName();
  6996. if (__mergedStore[classKey]) {
  6997. return __mergedStore[classKey];
  6998. }
  6999. __mergedStore[classKey] = {};
  7000. var store = __mergedStore[classKey];
  7001. var currentTarget = target;
  7002. var currentKey = classKey;
  7003. while (currentKey) {
  7004. var initialStore = __decoratorInitialStore[currentKey];
  7005. for (var property in initialStore) {
  7006. store[property] = initialStore[property];
  7007. }
  7008. var parent_1 = void 0;
  7009. var done = false;
  7010. do {
  7011. parent_1 = Object.getPrototypeOf(currentTarget);
  7012. if (!parent_1.getClassName) {
  7013. done = true;
  7014. break;
  7015. }
  7016. if (parent_1.getClassName() !== currentKey) {
  7017. break;
  7018. }
  7019. currentTarget = parent_1;
  7020. } while (parent_1);
  7021. if (done) {
  7022. break;
  7023. }
  7024. currentKey = parent_1.getClassName();
  7025. currentTarget = parent_1;
  7026. }
  7027. return store;
  7028. }
  7029. function generateSerializableMember(type, sourceName) {
  7030. return function (target, propertyKey) {
  7031. var classStore = getDirectStore(target);
  7032. if (!classStore[propertyKey]) {
  7033. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7034. }
  7035. };
  7036. }
  7037. function generateExpandMember(setCallback, targetKey) {
  7038. if (targetKey === void 0) { targetKey = null; }
  7039. return function (target, propertyKey) {
  7040. var key = targetKey || ("_" + propertyKey);
  7041. Object.defineProperty(target, propertyKey, {
  7042. get: function () {
  7043. return this[key];
  7044. },
  7045. set: function (value) {
  7046. if (this[key] === value) {
  7047. return;
  7048. }
  7049. this[key] = value;
  7050. target[setCallback].apply(this);
  7051. },
  7052. enumerable: true,
  7053. configurable: true
  7054. });
  7055. };
  7056. }
  7057. function expandToProperty(callback, targetKey) {
  7058. if (targetKey === void 0) { targetKey = null; }
  7059. return generateExpandMember(callback, targetKey);
  7060. }
  7061. BABYLON.expandToProperty = expandToProperty;
  7062. function serialize(sourceName) {
  7063. return generateSerializableMember(0, sourceName); // value member
  7064. }
  7065. BABYLON.serialize = serialize;
  7066. function serializeAsTexture(sourceName) {
  7067. return generateSerializableMember(1, sourceName); // texture member
  7068. }
  7069. BABYLON.serializeAsTexture = serializeAsTexture;
  7070. function serializeAsColor3(sourceName) {
  7071. return generateSerializableMember(2, sourceName); // color3 member
  7072. }
  7073. BABYLON.serializeAsColor3 = serializeAsColor3;
  7074. function serializeAsFresnelParameters(sourceName) {
  7075. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7076. }
  7077. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7078. function serializeAsVector2(sourceName) {
  7079. return generateSerializableMember(4, sourceName); // vector2 member
  7080. }
  7081. BABYLON.serializeAsVector2 = serializeAsVector2;
  7082. function serializeAsVector3(sourceName) {
  7083. return generateSerializableMember(5, sourceName); // vector3 member
  7084. }
  7085. BABYLON.serializeAsVector3 = serializeAsVector3;
  7086. function serializeAsMeshReference(sourceName) {
  7087. return generateSerializableMember(6, sourceName); // mesh reference member
  7088. }
  7089. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7090. function serializeAsColorCurves(sourceName) {
  7091. return generateSerializableMember(7, sourceName); // color curves
  7092. }
  7093. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7094. function serializeAsColor4(sourceName) {
  7095. return generateSerializableMember(8, sourceName); // color 4
  7096. }
  7097. BABYLON.serializeAsColor4 = serializeAsColor4;
  7098. function serializeAsImageProcessingConfiguration(sourceName) {
  7099. return generateSerializableMember(9, sourceName); // image processing
  7100. }
  7101. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7102. function serializeAsQuaternion(sourceName) {
  7103. return generateSerializableMember(10, sourceName); // quaternion member
  7104. }
  7105. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7106. var SerializationHelper = /** @class */ (function () {
  7107. function SerializationHelper() {
  7108. }
  7109. SerializationHelper.Serialize = function (entity, serializationObject) {
  7110. if (!serializationObject) {
  7111. serializationObject = {};
  7112. }
  7113. // Tags
  7114. if (BABYLON.Tags) {
  7115. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7116. }
  7117. var serializedProperties = getMergedStore(entity);
  7118. // Properties
  7119. for (var property in serializedProperties) {
  7120. var propertyDescriptor = serializedProperties[property];
  7121. var targetPropertyName = propertyDescriptor.sourceName || property;
  7122. var propertyType = propertyDescriptor.type;
  7123. var sourceProperty = entity[property];
  7124. if (sourceProperty !== undefined && sourceProperty !== null) {
  7125. switch (propertyType) {
  7126. case 0:// Value
  7127. serializationObject[targetPropertyName] = sourceProperty;
  7128. break;
  7129. case 1:// Texture
  7130. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7131. break;
  7132. case 2:// Color3
  7133. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7134. break;
  7135. case 3:// FresnelParameters
  7136. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7137. break;
  7138. case 4:// Vector2
  7139. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7140. break;
  7141. case 5:// Vector3
  7142. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7143. break;
  7144. case 6:// Mesh reference
  7145. serializationObject[targetPropertyName] = sourceProperty.id;
  7146. break;
  7147. case 7:// Color Curves
  7148. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7149. break;
  7150. case 8:// Color 4
  7151. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7152. break;
  7153. case 9:// Image Processing
  7154. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7155. break;
  7156. }
  7157. }
  7158. }
  7159. return serializationObject;
  7160. };
  7161. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7162. if (rootUrl === void 0) { rootUrl = null; }
  7163. var destination = creationFunction();
  7164. if (!rootUrl) {
  7165. rootUrl = "";
  7166. }
  7167. // Tags
  7168. if (BABYLON.Tags) {
  7169. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7170. }
  7171. var classStore = getMergedStore(destination);
  7172. // Properties
  7173. for (var property in classStore) {
  7174. var propertyDescriptor = classStore[property];
  7175. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7176. var propertyType = propertyDescriptor.type;
  7177. if (sourceProperty !== undefined && sourceProperty !== null) {
  7178. var dest = destination;
  7179. switch (propertyType) {
  7180. case 0:// Value
  7181. dest[property] = sourceProperty;
  7182. break;
  7183. case 1:// Texture
  7184. if (scene) {
  7185. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7186. }
  7187. break;
  7188. case 2:// Color3
  7189. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7190. break;
  7191. case 3:// FresnelParameters
  7192. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7193. break;
  7194. case 4:// Vector2
  7195. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7196. break;
  7197. case 5:// Vector3
  7198. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7199. break;
  7200. case 6:// Mesh reference
  7201. if (scene) {
  7202. dest[property] = scene.getLastMeshByID(sourceProperty);
  7203. }
  7204. break;
  7205. case 7:// Color Curves
  7206. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7207. break;
  7208. case 8:// Color 4
  7209. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7210. break;
  7211. case 9:// Image Processing
  7212. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7213. break;
  7214. }
  7215. }
  7216. }
  7217. return destination;
  7218. };
  7219. SerializationHelper.Clone = function (creationFunction, source) {
  7220. return _copySource(creationFunction, source, false);
  7221. };
  7222. SerializationHelper.Instanciate = function (creationFunction, source) {
  7223. return _copySource(creationFunction, source, true);
  7224. };
  7225. return SerializationHelper;
  7226. }());
  7227. BABYLON.SerializationHelper = SerializationHelper;
  7228. })(BABYLON || (BABYLON = {}));
  7229. //# sourceMappingURL=babylon.decorators.js.map
  7230. var BABYLON;
  7231. (function (BABYLON) {
  7232. /**
  7233. * Wrapper class for promise with external resolve and reject.
  7234. */
  7235. var Deferred = /** @class */ (function () {
  7236. /**
  7237. * Constructor for this deferred object.
  7238. */
  7239. function Deferred() {
  7240. var _this = this;
  7241. this.promise = new Promise(function (resolve, reject) {
  7242. _this._resolve = resolve;
  7243. _this._reject = reject;
  7244. });
  7245. }
  7246. Object.defineProperty(Deferred.prototype, "resolve", {
  7247. /**
  7248. * The resolve method of the promise associated with this deferred object.
  7249. */
  7250. get: function () {
  7251. return this._resolve;
  7252. },
  7253. enumerable: true,
  7254. configurable: true
  7255. });
  7256. Object.defineProperty(Deferred.prototype, "reject", {
  7257. /**
  7258. * The reject method of the promise associated with this deferred object.
  7259. */
  7260. get: function () {
  7261. return this._reject;
  7262. },
  7263. enumerable: true,
  7264. configurable: true
  7265. });
  7266. return Deferred;
  7267. }());
  7268. BABYLON.Deferred = Deferred;
  7269. })(BABYLON || (BABYLON = {}));
  7270. //# sourceMappingURL=babylon.deferred.js.map
  7271. var BABYLON;
  7272. (function (BABYLON) {
  7273. /**
  7274. * A class serves as a medium between the observable and its observers
  7275. */
  7276. var EventState = /** @class */ (function () {
  7277. /**
  7278. * Create a new EventState
  7279. * @param mask defines the mask associated with this state
  7280. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7281. * @param target defines the original target of the state
  7282. * @param currentTarget defines the current target of the state
  7283. */
  7284. function EventState(mask, skipNextObservers, target, currentTarget) {
  7285. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7286. this.initalize(mask, skipNextObservers, target, currentTarget);
  7287. }
  7288. /**
  7289. * Initialize the current event state
  7290. * @param mask defines the mask associated with this state
  7291. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7292. * @param target defines the original target of the state
  7293. * @param currentTarget defines the current target of the state
  7294. * @returns the current event state
  7295. */
  7296. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7297. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7298. this.mask = mask;
  7299. this.skipNextObservers = skipNextObservers;
  7300. this.target = target;
  7301. this.currentTarget = currentTarget;
  7302. return this;
  7303. };
  7304. return EventState;
  7305. }());
  7306. BABYLON.EventState = EventState;
  7307. /**
  7308. * Represent an Observer registered to a given Observable object.
  7309. */
  7310. var Observer = /** @class */ (function () {
  7311. /**
  7312. * Creates a new observer
  7313. * @param callback defines the callback to call when the observer is notified
  7314. * @param mask defines the mask of the observer (used to filter notifications)
  7315. * @param scope defines the current scope used to restore the JS context
  7316. */
  7317. function Observer(
  7318. /**
  7319. * Defines the callback to call when the observer is notified
  7320. */
  7321. callback,
  7322. /**
  7323. * Defines the mask of the observer (used to filter notifications)
  7324. */
  7325. mask,
  7326. /**
  7327. * Defines the current scope used to restore the JS context
  7328. */
  7329. scope) {
  7330. if (scope === void 0) { scope = null; }
  7331. this.callback = callback;
  7332. this.mask = mask;
  7333. this.scope = scope;
  7334. /** @ignore */
  7335. this._willBeUnregistered = false;
  7336. /**
  7337. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7338. */
  7339. this.unregisterOnNextCall = false;
  7340. }
  7341. return Observer;
  7342. }());
  7343. BABYLON.Observer = Observer;
  7344. /**
  7345. * Represent a list of observers registered to multiple Observables object.
  7346. */
  7347. var MultiObserver = /** @class */ (function () {
  7348. function MultiObserver() {
  7349. }
  7350. /**
  7351. * Release associated resources
  7352. */
  7353. MultiObserver.prototype.dispose = function () {
  7354. if (this._observers && this._observables) {
  7355. for (var index = 0; index < this._observers.length; index++) {
  7356. this._observables[index].remove(this._observers[index]);
  7357. }
  7358. }
  7359. this._observers = null;
  7360. this._observables = null;
  7361. };
  7362. /**
  7363. * Raise a callback when one of the observable will notify
  7364. * @param observables defines a list of observables to watch
  7365. * @param callback defines the callback to call on notification
  7366. * @param mask defines the mask used to filter notifications
  7367. * @param scope defines the current scope used to restore the JS context
  7368. * @returns the new MultiObserver
  7369. */
  7370. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7371. if (mask === void 0) { mask = -1; }
  7372. if (scope === void 0) { scope = null; }
  7373. var result = new MultiObserver();
  7374. result._observers = new Array();
  7375. result._observables = observables;
  7376. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7377. var observable = observables_1[_i];
  7378. var observer = observable.add(callback, mask, false, scope);
  7379. if (observer) {
  7380. result._observers.push(observer);
  7381. }
  7382. }
  7383. return result;
  7384. };
  7385. return MultiObserver;
  7386. }());
  7387. BABYLON.MultiObserver = MultiObserver;
  7388. /**
  7389. * The Observable class is a simple implementation of the Observable pattern.
  7390. * 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.
  7391. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7392. * 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).
  7393. * 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.
  7394. */
  7395. var Observable = /** @class */ (function () {
  7396. /**
  7397. * Creates a new observable
  7398. * @param onObserverAdded defines a callback to call when a new observer is added
  7399. */
  7400. function Observable(onObserverAdded) {
  7401. this._observers = new Array();
  7402. this._eventState = new EventState(0);
  7403. if (onObserverAdded) {
  7404. this._onObserverAdded = onObserverAdded;
  7405. }
  7406. }
  7407. /**
  7408. * Create a new Observer with the specified callback
  7409. * @param callback the callback that will be executed for that Observer
  7410. * @param mask the mask used to filter observers
  7411. * @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.
  7412. * @param scope optional scope for the callback to be called from
  7413. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7414. * @returns the new observer created for the callback
  7415. */
  7416. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7417. if (mask === void 0) { mask = -1; }
  7418. if (insertFirst === void 0) { insertFirst = false; }
  7419. if (scope === void 0) { scope = null; }
  7420. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7421. if (!callback) {
  7422. return null;
  7423. }
  7424. var observer = new Observer(callback, mask, scope);
  7425. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7426. if (insertFirst) {
  7427. this._observers.unshift(observer);
  7428. }
  7429. else {
  7430. this._observers.push(observer);
  7431. }
  7432. if (this._onObserverAdded) {
  7433. this._onObserverAdded(observer);
  7434. }
  7435. return observer;
  7436. };
  7437. /**
  7438. * Remove an Observer from the Observable object
  7439. * @param observer the instance of the Observer to remove
  7440. * @returns false if it doesn't belong to this Observable
  7441. */
  7442. Observable.prototype.remove = function (observer) {
  7443. if (!observer) {
  7444. return false;
  7445. }
  7446. var index = this._observers.indexOf(observer);
  7447. if (index !== -1) {
  7448. this._observers.splice(index, 1);
  7449. return true;
  7450. }
  7451. return false;
  7452. };
  7453. /**
  7454. * Remove a callback from the Observable object
  7455. * @param callback the callback to remove
  7456. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7457. * @returns false if it doesn't belong to this Observable
  7458. */
  7459. Observable.prototype.removeCallback = function (callback, scope) {
  7460. for (var index = 0; index < this._observers.length; index++) {
  7461. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7462. this._observers.splice(index, 1);
  7463. return true;
  7464. }
  7465. }
  7466. return false;
  7467. };
  7468. Observable.prototype._deferUnregister = function (observer) {
  7469. var _this = this;
  7470. observer.unregisterOnNextCall = false;
  7471. observer._willBeUnregistered = true;
  7472. BABYLON.Tools.SetImmediate(function () {
  7473. _this.remove(observer);
  7474. });
  7475. };
  7476. /**
  7477. * Notify all Observers by calling their respective callback with the given data
  7478. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7479. * @param eventData defines the data to send to all observers
  7480. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7481. * @param target defines the original target of the state
  7482. * @param currentTarget defines the current target of the state
  7483. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7484. */
  7485. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7486. if (mask === void 0) { mask = -1; }
  7487. if (!this._observers.length) {
  7488. return true;
  7489. }
  7490. var state = this._eventState;
  7491. state.mask = mask;
  7492. state.target = target;
  7493. state.currentTarget = currentTarget;
  7494. state.skipNextObservers = false;
  7495. state.lastReturnValue = eventData;
  7496. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7497. var obs = _a[_i];
  7498. if (obs._willBeUnregistered) {
  7499. continue;
  7500. }
  7501. if (obs.mask & mask) {
  7502. if (obs.scope) {
  7503. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7504. }
  7505. else {
  7506. state.lastReturnValue = obs.callback(eventData, state);
  7507. }
  7508. if (obs.unregisterOnNextCall) {
  7509. this._deferUnregister(obs);
  7510. }
  7511. }
  7512. if (state.skipNextObservers) {
  7513. return false;
  7514. }
  7515. }
  7516. return true;
  7517. };
  7518. /**
  7519. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7520. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7521. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7522. * and it is crucial that all callbacks will be executed.
  7523. * The order of the callbacks is kept, callbacks are not executed parallel.
  7524. *
  7525. * @param eventData The data to be sent to each callback
  7526. * @param mask is used to filter observers defaults to -1
  7527. * @param target defines the callback target (see EventState)
  7528. * @param currentTarget defines he current object in the bubbling phase
  7529. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7530. */
  7531. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7532. var _this = this;
  7533. if (mask === void 0) { mask = -1; }
  7534. // create an empty promise
  7535. var p = Promise.resolve(eventData);
  7536. // no observers? return this promise.
  7537. if (!this._observers.length) {
  7538. return p;
  7539. }
  7540. var state = this._eventState;
  7541. state.mask = mask;
  7542. state.target = target;
  7543. state.currentTarget = currentTarget;
  7544. state.skipNextObservers = false;
  7545. // execute one callback after another (not using Promise.all, the order is important)
  7546. this._observers.forEach(function (obs) {
  7547. if (state.skipNextObservers) {
  7548. return;
  7549. }
  7550. if (obs._willBeUnregistered) {
  7551. return;
  7552. }
  7553. if (obs.mask & mask) {
  7554. if (obs.scope) {
  7555. p = p.then(function (lastReturnedValue) {
  7556. state.lastReturnValue = lastReturnedValue;
  7557. return obs.callback.apply(obs.scope, [eventData, state]);
  7558. });
  7559. }
  7560. else {
  7561. p = p.then(function (lastReturnedValue) {
  7562. state.lastReturnValue = lastReturnedValue;
  7563. return obs.callback(eventData, state);
  7564. });
  7565. }
  7566. if (obs.unregisterOnNextCall) {
  7567. _this._deferUnregister(obs);
  7568. }
  7569. }
  7570. });
  7571. // return the eventData
  7572. return p.then(function () { return eventData; });
  7573. };
  7574. /**
  7575. * Notify a specific observer
  7576. * @param observer defines the observer to notify
  7577. * @param eventData defines the data to be sent to each callback
  7578. * @param mask is used to filter observers defaults to -1
  7579. */
  7580. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7581. if (mask === void 0) { mask = -1; }
  7582. var state = this._eventState;
  7583. state.mask = mask;
  7584. state.skipNextObservers = false;
  7585. observer.callback(eventData, state);
  7586. };
  7587. /**
  7588. * Gets a boolean indicating if the observable has at least one observer
  7589. * @returns true is the Observable has at least one Observer registered
  7590. */
  7591. Observable.prototype.hasObservers = function () {
  7592. return this._observers.length > 0;
  7593. };
  7594. /**
  7595. * Clear the list of observers
  7596. */
  7597. Observable.prototype.clear = function () {
  7598. this._observers = new Array();
  7599. this._onObserverAdded = null;
  7600. };
  7601. /**
  7602. * Clone the current observable
  7603. * @returns a new observable
  7604. */
  7605. Observable.prototype.clone = function () {
  7606. var result = new Observable();
  7607. result._observers = this._observers.slice(0);
  7608. return result;
  7609. };
  7610. /**
  7611. * Does this observable handles observer registered with a given mask
  7612. * @param mask defines the mask to be tested
  7613. * @return whether or not one observer registered with the given mask is handeled
  7614. **/
  7615. Observable.prototype.hasSpecificMask = function (mask) {
  7616. if (mask === void 0) { mask = -1; }
  7617. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7618. var obs = _a[_i];
  7619. if (obs.mask & mask || obs.mask === mask) {
  7620. return true;
  7621. }
  7622. }
  7623. return false;
  7624. };
  7625. return Observable;
  7626. }());
  7627. BABYLON.Observable = Observable;
  7628. })(BABYLON || (BABYLON = {}));
  7629. //# sourceMappingURL=babylon.observable.js.map
  7630. var BABYLON;
  7631. (function (BABYLON) {
  7632. var SmartArray = /** @class */ (function () {
  7633. function SmartArray(capacity) {
  7634. this.length = 0;
  7635. this.data = new Array(capacity);
  7636. this._id = SmartArray._GlobalId++;
  7637. }
  7638. SmartArray.prototype.push = function (value) {
  7639. this.data[this.length++] = value;
  7640. if (this.length > this.data.length) {
  7641. this.data.length *= 2;
  7642. }
  7643. };
  7644. SmartArray.prototype.forEach = function (func) {
  7645. for (var index = 0; index < this.length; index++) {
  7646. func(this.data[index]);
  7647. }
  7648. };
  7649. SmartArray.prototype.sort = function (compareFn) {
  7650. this.data.sort(compareFn);
  7651. };
  7652. SmartArray.prototype.reset = function () {
  7653. this.length = 0;
  7654. };
  7655. SmartArray.prototype.dispose = function () {
  7656. this.reset();
  7657. if (this.data) {
  7658. this.data.length = 0;
  7659. this.data = [];
  7660. }
  7661. };
  7662. SmartArray.prototype.concat = function (array) {
  7663. if (array.length === 0) {
  7664. return;
  7665. }
  7666. if (this.length + array.length > this.data.length) {
  7667. this.data.length = (this.length + array.length) * 2;
  7668. }
  7669. for (var index = 0; index < array.length; index++) {
  7670. this.data[this.length++] = (array.data || array)[index];
  7671. }
  7672. };
  7673. SmartArray.prototype.indexOf = function (value) {
  7674. var position = this.data.indexOf(value);
  7675. if (position >= this.length) {
  7676. return -1;
  7677. }
  7678. return position;
  7679. };
  7680. SmartArray.prototype.contains = function (value) {
  7681. return this.data.indexOf(value) !== -1;
  7682. };
  7683. // Statics
  7684. SmartArray._GlobalId = 0;
  7685. return SmartArray;
  7686. }());
  7687. BABYLON.SmartArray = SmartArray;
  7688. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7689. __extends(SmartArrayNoDuplicate, _super);
  7690. function SmartArrayNoDuplicate() {
  7691. var _this = _super !== null && _super.apply(this, arguments) || this;
  7692. _this._duplicateId = 0;
  7693. return _this;
  7694. }
  7695. SmartArrayNoDuplicate.prototype.push = function (value) {
  7696. _super.prototype.push.call(this, value);
  7697. if (!value.__smartArrayFlags) {
  7698. value.__smartArrayFlags = {};
  7699. }
  7700. value.__smartArrayFlags[this._id] = this._duplicateId;
  7701. };
  7702. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7703. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7704. return false;
  7705. }
  7706. this.push(value);
  7707. return true;
  7708. };
  7709. SmartArrayNoDuplicate.prototype.reset = function () {
  7710. _super.prototype.reset.call(this);
  7711. this._duplicateId++;
  7712. };
  7713. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7714. if (array.length === 0) {
  7715. return;
  7716. }
  7717. if (this.length + array.length > this.data.length) {
  7718. this.data.length = (this.length + array.length) * 2;
  7719. }
  7720. for (var index = 0; index < array.length; index++) {
  7721. var item = (array.data || array)[index];
  7722. this.pushNoDuplicate(item);
  7723. }
  7724. };
  7725. return SmartArrayNoDuplicate;
  7726. }(SmartArray));
  7727. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7728. })(BABYLON || (BABYLON = {}));
  7729. //# sourceMappingURL=babylon.smartArray.js.map
  7730. var BABYLON;
  7731. (function (BABYLON) {
  7732. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7733. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7734. var LoadFileError = /** @class */ (function (_super) {
  7735. __extends(LoadFileError, _super);
  7736. function LoadFileError(message, request) {
  7737. var _this = _super.call(this, message) || this;
  7738. _this.request = request;
  7739. _this.name = "LoadFileError";
  7740. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7741. return _this;
  7742. }
  7743. // Polyfill for Object.setPrototypeOf if necessary.
  7744. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7745. return LoadFileError;
  7746. }(Error));
  7747. BABYLON.LoadFileError = LoadFileError;
  7748. var RetryStrategy = /** @class */ (function () {
  7749. function RetryStrategy() {
  7750. }
  7751. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7752. if (maxRetries === void 0) { maxRetries = 3; }
  7753. if (baseInterval === void 0) { baseInterval = 500; }
  7754. return function (url, request, retryIndex) {
  7755. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7756. return -1;
  7757. }
  7758. return Math.pow(2, retryIndex) * baseInterval;
  7759. };
  7760. };
  7761. return RetryStrategy;
  7762. }());
  7763. BABYLON.RetryStrategy = RetryStrategy;
  7764. // Screenshots
  7765. var screenshotCanvas;
  7766. var cloneValue = function (source, destinationObject) {
  7767. if (!source)
  7768. return null;
  7769. if (source instanceof BABYLON.Mesh) {
  7770. return null;
  7771. }
  7772. if (source instanceof BABYLON.SubMesh) {
  7773. return source.clone(destinationObject);
  7774. }
  7775. else if (source.clone) {
  7776. return source.clone();
  7777. }
  7778. return null;
  7779. };
  7780. var Tools = /** @class */ (function () {
  7781. function Tools() {
  7782. }
  7783. /**
  7784. * Interpolates between a and b via alpha
  7785. * @param a The lower value (returned when alpha = 0)
  7786. * @param b The upper value (returned when alpha = 1)
  7787. * @param alpha The interpolation-factor
  7788. * @return The mixed value
  7789. */
  7790. Tools.Mix = function (a, b, alpha) {
  7791. return a * (1 - alpha) + b * alpha;
  7792. };
  7793. Tools.Instantiate = function (className) {
  7794. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7795. return Tools.RegisteredExternalClasses[className];
  7796. }
  7797. var arr = className.split(".");
  7798. var fn = (window || this);
  7799. for (var i = 0, len = arr.length; i < len; i++) {
  7800. fn = fn[arr[i]];
  7801. }
  7802. if (typeof fn !== "function") {
  7803. return null;
  7804. }
  7805. return fn;
  7806. };
  7807. /**
  7808. * Provides a slice function that will work even on IE
  7809. * @param data defines the array to slice
  7810. * @returns the new sliced array
  7811. */
  7812. Tools.Slice = function (data) {
  7813. if (data.slice) {
  7814. return data.slice();
  7815. }
  7816. return Array.prototype.slice.call(data);
  7817. };
  7818. Tools.SetImmediate = function (action) {
  7819. if (window.setImmediate) {
  7820. window.setImmediate(action);
  7821. }
  7822. else {
  7823. setTimeout(action, 1);
  7824. }
  7825. };
  7826. Tools.IsExponentOfTwo = function (value) {
  7827. var count = 1;
  7828. do {
  7829. count *= 2;
  7830. } while (count < value);
  7831. return count === value;
  7832. };
  7833. /**
  7834. * Find the next highest power of two.
  7835. * @param x Number to start search from.
  7836. * @return Next highest power of two.
  7837. */
  7838. Tools.CeilingPOT = function (x) {
  7839. x--;
  7840. x |= x >> 1;
  7841. x |= x >> 2;
  7842. x |= x >> 4;
  7843. x |= x >> 8;
  7844. x |= x >> 16;
  7845. x++;
  7846. return x;
  7847. };
  7848. /**
  7849. * Find the next lowest power of two.
  7850. * @param x Number to start search from.
  7851. * @return Next lowest power of two.
  7852. */
  7853. Tools.FloorPOT = function (x) {
  7854. x = x | (x >> 1);
  7855. x = x | (x >> 2);
  7856. x = x | (x >> 4);
  7857. x = x | (x >> 8);
  7858. x = x | (x >> 16);
  7859. return x - (x >> 1);
  7860. };
  7861. /**
  7862. * Find the nearest power of two.
  7863. * @param x Number to start search from.
  7864. * @return Next nearest power of two.
  7865. */
  7866. Tools.NearestPOT = function (x) {
  7867. var c = Tools.CeilingPOT(x);
  7868. var f = Tools.FloorPOT(x);
  7869. return (c - x) > (x - f) ? f : c;
  7870. };
  7871. Tools.GetExponentOfTwo = function (value, max, mode) {
  7872. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7873. var pot;
  7874. switch (mode) {
  7875. case BABYLON.Engine.SCALEMODE_FLOOR:
  7876. pot = Tools.FloorPOT(value);
  7877. break;
  7878. case BABYLON.Engine.SCALEMODE_NEAREST:
  7879. pot = Tools.NearestPOT(value);
  7880. break;
  7881. case BABYLON.Engine.SCALEMODE_CEILING:
  7882. default:
  7883. pot = Tools.CeilingPOT(value);
  7884. break;
  7885. }
  7886. return Math.min(pot, max);
  7887. };
  7888. Tools.GetFilename = function (path) {
  7889. var index = path.lastIndexOf("/");
  7890. if (index < 0)
  7891. return path;
  7892. return path.substring(index + 1);
  7893. };
  7894. /**
  7895. * Extracts the "folder" part of a path (everything before the filename).
  7896. * @param uri The URI to extract the info from
  7897. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7898. * @returns The "folder" part of the path
  7899. */
  7900. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7901. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7902. var index = uri.lastIndexOf("/");
  7903. if (index < 0) {
  7904. if (returnUnchangedIfNoSlash) {
  7905. return uri;
  7906. }
  7907. return "";
  7908. }
  7909. return uri.substring(0, index + 1);
  7910. };
  7911. Tools.GetDOMTextContent = function (element) {
  7912. var result = "";
  7913. var child = element.firstChild;
  7914. while (child) {
  7915. if (child.nodeType === 3) {
  7916. result += child.textContent;
  7917. }
  7918. child = child.nextSibling;
  7919. }
  7920. return result;
  7921. };
  7922. Tools.ToDegrees = function (angle) {
  7923. return angle * 180 / Math.PI;
  7924. };
  7925. Tools.ToRadians = function (angle) {
  7926. return angle * Math.PI / 180;
  7927. };
  7928. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7929. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7930. var output = "";
  7931. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7932. var i = 0;
  7933. var bytes = new Uint8Array(buffer);
  7934. while (i < bytes.length) {
  7935. chr1 = bytes[i++];
  7936. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7937. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7938. enc1 = chr1 >> 2;
  7939. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7940. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7941. enc4 = chr3 & 63;
  7942. if (isNaN(chr2)) {
  7943. enc3 = enc4 = 64;
  7944. }
  7945. else if (isNaN(chr3)) {
  7946. enc4 = 64;
  7947. }
  7948. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7949. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7950. }
  7951. return "data:image/png;base64," + output;
  7952. };
  7953. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7954. if (bias === void 0) { bias = null; }
  7955. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7956. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7957. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7958. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7959. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7960. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7961. }
  7962. if (bias) {
  7963. minimum.x -= minimum.x * bias.x + bias.y;
  7964. minimum.y -= minimum.y * bias.x + bias.y;
  7965. minimum.z -= minimum.z * bias.x + bias.y;
  7966. maximum.x += maximum.x * bias.x + bias.y;
  7967. maximum.y += maximum.y * bias.x + bias.y;
  7968. maximum.z += maximum.z * bias.x + bias.y;
  7969. }
  7970. return {
  7971. minimum: minimum,
  7972. maximum: maximum
  7973. };
  7974. };
  7975. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7976. if (bias === void 0) { bias = null; }
  7977. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7978. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7979. if (!stride) {
  7980. stride = 3;
  7981. }
  7982. for (var index = start; index < start + count; index++) {
  7983. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7984. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7985. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7986. }
  7987. if (bias) {
  7988. minimum.x -= minimum.x * bias.x + bias.y;
  7989. minimum.y -= minimum.y * bias.x + bias.y;
  7990. minimum.z -= minimum.z * bias.x + bias.y;
  7991. maximum.x += maximum.x * bias.x + bias.y;
  7992. maximum.y += maximum.y * bias.x + bias.y;
  7993. maximum.z += maximum.z * bias.x + bias.y;
  7994. }
  7995. return {
  7996. minimum: minimum,
  7997. maximum: maximum
  7998. };
  7999. };
  8000. Tools.Vector2ArrayFeeder = function (array) {
  8001. return function (index) {
  8002. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8003. var length = isFloatArray ? array.length / 2 : array.length;
  8004. if (index >= length) {
  8005. return null;
  8006. }
  8007. if (isFloatArray) {
  8008. var fa = array;
  8009. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8010. }
  8011. var a = array;
  8012. return a[index];
  8013. };
  8014. };
  8015. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8016. if (bias === void 0) { bias = null; }
  8017. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8018. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8019. var i = 0;
  8020. var cur = feeder(i++);
  8021. while (cur) {
  8022. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8023. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8024. cur = feeder(i++);
  8025. }
  8026. if (bias) {
  8027. minimum.x -= minimum.x * bias.x + bias.y;
  8028. minimum.y -= minimum.y * bias.x + bias.y;
  8029. maximum.x += maximum.x * bias.x + bias.y;
  8030. maximum.y += maximum.y * bias.x + bias.y;
  8031. }
  8032. return {
  8033. minimum: minimum,
  8034. maximum: maximum
  8035. };
  8036. };
  8037. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8038. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8039. return null;
  8040. return Array.isArray(obj) ? obj : [obj];
  8041. };
  8042. // Misc.
  8043. Tools.GetPointerPrefix = function () {
  8044. var eventPrefix = "pointer";
  8045. // Check if pointer events are supported
  8046. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8047. eventPrefix = "mouse";
  8048. }
  8049. return eventPrefix;
  8050. };
  8051. /**
  8052. * @param func - the function to be called
  8053. * @param requester - the object that will request the next frame. Falls back to window.
  8054. */
  8055. Tools.QueueNewFrame = function (func, requester) {
  8056. if (!Tools.IsWindowObjectExist()) {
  8057. return setTimeout(func, 16);
  8058. }
  8059. if (!requester) {
  8060. requester = window;
  8061. }
  8062. if (requester.requestAnimationFrame) {
  8063. return requester.requestAnimationFrame(func);
  8064. }
  8065. else if (requester.msRequestAnimationFrame) {
  8066. return requester.msRequestAnimationFrame(func);
  8067. }
  8068. else if (requester.webkitRequestAnimationFrame) {
  8069. return requester.webkitRequestAnimationFrame(func);
  8070. }
  8071. else if (requester.mozRequestAnimationFrame) {
  8072. return requester.mozRequestAnimationFrame(func);
  8073. }
  8074. else if (requester.oRequestAnimationFrame) {
  8075. return requester.oRequestAnimationFrame(func);
  8076. }
  8077. else {
  8078. return window.setTimeout(func, 16);
  8079. }
  8080. };
  8081. Tools.RequestFullscreen = function (element) {
  8082. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8083. if (!requestFunction)
  8084. return;
  8085. requestFunction.call(element);
  8086. };
  8087. Tools.ExitFullscreen = function () {
  8088. if (document.exitFullscreen) {
  8089. document.exitFullscreen();
  8090. }
  8091. else if (document.mozCancelFullScreen) {
  8092. document.mozCancelFullScreen();
  8093. }
  8094. else if (document.webkitCancelFullScreen) {
  8095. document.webkitCancelFullScreen();
  8096. }
  8097. else if (document.msCancelFullScreen) {
  8098. document.msCancelFullScreen();
  8099. }
  8100. };
  8101. Tools.SetCorsBehavior = function (url, element) {
  8102. if (url && url.indexOf("data:") === 0) {
  8103. return;
  8104. }
  8105. if (Tools.CorsBehavior) {
  8106. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8107. element.crossOrigin = Tools.CorsBehavior;
  8108. }
  8109. else {
  8110. var result = Tools.CorsBehavior(url);
  8111. if (result) {
  8112. element.crossOrigin = result;
  8113. }
  8114. }
  8115. }
  8116. };
  8117. // External files
  8118. Tools.CleanUrl = function (url) {
  8119. url = url.replace(/#/mg, "%23");
  8120. return url;
  8121. };
  8122. Tools.LoadImage = function (url, onLoad, onError, database) {
  8123. if (url instanceof ArrayBuffer) {
  8124. url = Tools.EncodeArrayBufferTobase64(url);
  8125. }
  8126. url = Tools.CleanUrl(url);
  8127. url = Tools.PreprocessUrl(url);
  8128. var img = new Image();
  8129. Tools.SetCorsBehavior(url, img);
  8130. var loadHandler = function () {
  8131. img.removeEventListener("load", loadHandler);
  8132. img.removeEventListener("error", errorHandler);
  8133. onLoad(img);
  8134. };
  8135. var errorHandler = function (err) {
  8136. img.removeEventListener("load", loadHandler);
  8137. img.removeEventListener("error", errorHandler);
  8138. Tools.Error("Error while trying to load image: " + url);
  8139. if (onError) {
  8140. onError("Error while trying to load image: " + url, err);
  8141. }
  8142. };
  8143. img.addEventListener("load", loadHandler);
  8144. img.addEventListener("error", errorHandler);
  8145. var noIndexedDB = function () {
  8146. img.src = url;
  8147. };
  8148. var loadFromIndexedDB = function () {
  8149. if (database) {
  8150. database.loadImageFromDB(url, img);
  8151. }
  8152. };
  8153. //ANY database to do!
  8154. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8155. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8156. }
  8157. else {
  8158. if (url.indexOf("file:") !== -1) {
  8159. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8160. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8161. try {
  8162. var blobURL;
  8163. try {
  8164. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8165. }
  8166. catch (ex) {
  8167. // Chrome doesn't support oneTimeOnly parameter
  8168. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8169. }
  8170. img.src = blobURL;
  8171. }
  8172. catch (e) {
  8173. img.src = "";
  8174. }
  8175. return img;
  8176. }
  8177. }
  8178. noIndexedDB();
  8179. }
  8180. return img;
  8181. };
  8182. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8183. url = Tools.CleanUrl(url);
  8184. url = Tools.PreprocessUrl(url);
  8185. // If file and file input are set
  8186. if (url.indexOf("file:") !== -1) {
  8187. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8188. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8189. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8190. }
  8191. }
  8192. var loadUrl = Tools.BaseUrl + url;
  8193. var aborted = false;
  8194. var fileRequest = {
  8195. onCompleteObservable: new BABYLON.Observable(),
  8196. abort: function () { return aborted = true; },
  8197. };
  8198. var requestFile = function () {
  8199. var request = new XMLHttpRequest();
  8200. var retryHandle = null;
  8201. fileRequest.abort = function () {
  8202. aborted = true;
  8203. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8204. request.abort();
  8205. }
  8206. if (retryHandle !== null) {
  8207. clearTimeout(retryHandle);
  8208. retryHandle = null;
  8209. }
  8210. };
  8211. var retryLoop = function (retryIndex) {
  8212. request.open('GET', loadUrl, true);
  8213. if (useArrayBuffer) {
  8214. request.responseType = "arraybuffer";
  8215. }
  8216. if (onProgress) {
  8217. request.addEventListener("progress", onProgress);
  8218. }
  8219. var onLoadEnd = function () {
  8220. request.removeEventListener("loadend", onLoadEnd);
  8221. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8222. fileRequest.onCompleteObservable.clear();
  8223. };
  8224. request.addEventListener("loadend", onLoadEnd);
  8225. var onReadyStateChange = function () {
  8226. if (aborted) {
  8227. return;
  8228. }
  8229. // In case of undefined state in some browsers.
  8230. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8231. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8232. request.removeEventListener("readystatechange", onReadyStateChange);
  8233. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8234. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8235. return;
  8236. }
  8237. var retryStrategy = Tools.DefaultRetryStrategy;
  8238. if (retryStrategy) {
  8239. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8240. if (waitTime !== -1) {
  8241. // Prevent the request from completing for retry.
  8242. request.removeEventListener("loadend", onLoadEnd);
  8243. request = new XMLHttpRequest();
  8244. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8245. return;
  8246. }
  8247. }
  8248. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8249. if (onError) {
  8250. onError(request, e);
  8251. }
  8252. else {
  8253. throw e;
  8254. }
  8255. }
  8256. };
  8257. request.addEventListener("readystatechange", onReadyStateChange);
  8258. request.send();
  8259. };
  8260. retryLoop(0);
  8261. };
  8262. // Caching all files
  8263. if (database && database.enableSceneOffline) {
  8264. var noIndexedDB_1 = function () {
  8265. if (!aborted) {
  8266. requestFile();
  8267. }
  8268. };
  8269. var loadFromIndexedDB = function () {
  8270. // TODO: database needs to support aborting and should return a IFileRequest
  8271. if (aborted) {
  8272. return;
  8273. }
  8274. if (database) {
  8275. database.loadFileFromDB(url, function (data) {
  8276. if (!aborted) {
  8277. onSuccess(data);
  8278. }
  8279. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8280. }, onProgress ? function (event) {
  8281. if (!aborted) {
  8282. onProgress(event);
  8283. }
  8284. } : undefined, noIndexedDB_1, useArrayBuffer);
  8285. }
  8286. };
  8287. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8288. }
  8289. else {
  8290. requestFile();
  8291. }
  8292. return fileRequest;
  8293. };
  8294. /**
  8295. * Load a script (identified by an url). When the url returns, the
  8296. * content of this file is added into a new script element, attached to the DOM (body element)
  8297. */
  8298. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8299. var head = document.getElementsByTagName('head')[0];
  8300. var script = document.createElement('script');
  8301. script.type = 'text/javascript';
  8302. script.src = scriptUrl;
  8303. script.onload = function () {
  8304. if (onSuccess) {
  8305. onSuccess();
  8306. }
  8307. };
  8308. script.onerror = function (e) {
  8309. if (onError) {
  8310. onError("Unable to load script", e);
  8311. }
  8312. };
  8313. head.appendChild(script);
  8314. };
  8315. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8316. var reader = new FileReader();
  8317. var request = {
  8318. onCompleteObservable: new BABYLON.Observable(),
  8319. abort: function () { return reader.abort(); },
  8320. };
  8321. reader.onloadend = function (e) {
  8322. request.onCompleteObservable.notifyObservers(request);
  8323. };
  8324. reader.onload = function (e) {
  8325. //target doesn't have result from ts 1.3
  8326. callback(e.target['result']);
  8327. };
  8328. reader.onprogress = progressCallback;
  8329. reader.readAsDataURL(fileToLoad);
  8330. return request;
  8331. };
  8332. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8333. var reader = new FileReader();
  8334. var request = {
  8335. onCompleteObservable: new BABYLON.Observable(),
  8336. abort: function () { return reader.abort(); },
  8337. };
  8338. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8339. reader.onerror = function (e) {
  8340. Tools.Log("Error while reading file: " + fileToLoad.name);
  8341. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8342. };
  8343. reader.onload = function (e) {
  8344. //target doesn't have result from ts 1.3
  8345. callback(e.target['result']);
  8346. };
  8347. if (progressCallBack) {
  8348. reader.onprogress = progressCallBack;
  8349. }
  8350. if (!useArrayBuffer) {
  8351. // Asynchronous read
  8352. reader.readAsText(fileToLoad);
  8353. }
  8354. else {
  8355. reader.readAsArrayBuffer(fileToLoad);
  8356. }
  8357. return request;
  8358. };
  8359. //returns a downloadable url to a file content.
  8360. Tools.FileAsURL = function (content) {
  8361. var fileBlob = new Blob([content]);
  8362. var url = window.URL || window.webkitURL;
  8363. var link = url.createObjectURL(fileBlob);
  8364. return link;
  8365. };
  8366. // Misc.
  8367. Tools.Format = function (value, decimals) {
  8368. if (decimals === void 0) { decimals = 2; }
  8369. return value.toFixed(decimals);
  8370. };
  8371. Tools.CheckExtends = function (v, min, max) {
  8372. if (v.x < min.x)
  8373. min.x = v.x;
  8374. if (v.y < min.y)
  8375. min.y = v.y;
  8376. if (v.z < min.z)
  8377. min.z = v.z;
  8378. if (v.x > max.x)
  8379. max.x = v.x;
  8380. if (v.y > max.y)
  8381. max.y = v.y;
  8382. if (v.z > max.z)
  8383. max.z = v.z;
  8384. };
  8385. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8386. for (var prop in source) {
  8387. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8388. continue;
  8389. }
  8390. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8391. continue;
  8392. }
  8393. var sourceValue = source[prop];
  8394. var typeOfSourceValue = typeof sourceValue;
  8395. if (typeOfSourceValue === "function") {
  8396. continue;
  8397. }
  8398. if (typeOfSourceValue === "object") {
  8399. if (sourceValue instanceof Array) {
  8400. destination[prop] = [];
  8401. if (sourceValue.length > 0) {
  8402. if (typeof sourceValue[0] == "object") {
  8403. for (var index = 0; index < sourceValue.length; index++) {
  8404. var clonedValue = cloneValue(sourceValue[index], destination);
  8405. if (destination[prop].indexOf(clonedValue) === -1) {
  8406. destination[prop].push(clonedValue);
  8407. }
  8408. }
  8409. }
  8410. else {
  8411. destination[prop] = sourceValue.slice(0);
  8412. }
  8413. }
  8414. }
  8415. else {
  8416. destination[prop] = cloneValue(sourceValue, destination);
  8417. }
  8418. }
  8419. else {
  8420. destination[prop] = sourceValue;
  8421. }
  8422. }
  8423. };
  8424. Tools.IsEmpty = function (obj) {
  8425. for (var i in obj) {
  8426. if (obj.hasOwnProperty(i)) {
  8427. return false;
  8428. }
  8429. }
  8430. return true;
  8431. };
  8432. Tools.RegisterTopRootEvents = function (events) {
  8433. for (var index = 0; index < events.length; index++) {
  8434. var event = events[index];
  8435. window.addEventListener(event.name, event.handler, false);
  8436. try {
  8437. if (window.parent) {
  8438. window.parent.addEventListener(event.name, event.handler, false);
  8439. }
  8440. }
  8441. catch (e) {
  8442. // Silently fails...
  8443. }
  8444. }
  8445. };
  8446. Tools.UnregisterTopRootEvents = function (events) {
  8447. for (var index = 0; index < events.length; index++) {
  8448. var event = events[index];
  8449. window.removeEventListener(event.name, event.handler);
  8450. try {
  8451. if (window.parent) {
  8452. window.parent.removeEventListener(event.name, event.handler);
  8453. }
  8454. }
  8455. catch (e) {
  8456. // Silently fails...
  8457. }
  8458. }
  8459. };
  8460. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8461. if (mimeType === void 0) { mimeType = "image/png"; }
  8462. // Read the contents of the framebuffer
  8463. var numberOfChannelsByLine = width * 4;
  8464. var halfHeight = height / 2;
  8465. //Reading datas from WebGL
  8466. var data = engine.readPixels(0, 0, width, height);
  8467. //To flip image on Y axis.
  8468. for (var i = 0; i < halfHeight; i++) {
  8469. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8470. var currentCell = j + i * numberOfChannelsByLine;
  8471. var targetLine = height - i - 1;
  8472. var targetCell = j + targetLine * numberOfChannelsByLine;
  8473. var temp = data[currentCell];
  8474. data[currentCell] = data[targetCell];
  8475. data[targetCell] = temp;
  8476. }
  8477. }
  8478. // Create a 2D canvas to store the result
  8479. if (!screenshotCanvas) {
  8480. screenshotCanvas = document.createElement('canvas');
  8481. }
  8482. screenshotCanvas.width = width;
  8483. screenshotCanvas.height = height;
  8484. var context = screenshotCanvas.getContext('2d');
  8485. if (context) {
  8486. // Copy the pixels to a 2D canvas
  8487. var imageData = context.createImageData(width, height);
  8488. var castData = (imageData.data);
  8489. castData.set(data);
  8490. context.putImageData(imageData, 0, 0);
  8491. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8492. }
  8493. };
  8494. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8495. if (mimeType === void 0) { mimeType = "image/png"; }
  8496. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8497. if (successCallback) {
  8498. successCallback(base64Image);
  8499. }
  8500. else {
  8501. // We need HTMLCanvasElement.toBlob for HD screenshots
  8502. if (!screenshotCanvas.toBlob) {
  8503. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8504. screenshotCanvas.toBlob = function (callback, type, quality) {
  8505. var _this = this;
  8506. setTimeout(function () {
  8507. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8508. for (var i = 0; i < len; i++) {
  8509. arr[i] = binStr.charCodeAt(i);
  8510. }
  8511. callback(new Blob([arr], { type: type || 'image/png' }));
  8512. });
  8513. };
  8514. }
  8515. screenshotCanvas.toBlob(function (blob) {
  8516. var url = URL.createObjectURL(blob);
  8517. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8518. if (("download" in document.createElement("a"))) {
  8519. var a = window.document.createElement("a");
  8520. a.href = url;
  8521. if (fileName) {
  8522. a.setAttribute("download", fileName);
  8523. }
  8524. else {
  8525. var date = new Date();
  8526. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8527. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8528. }
  8529. window.document.body.appendChild(a);
  8530. a.addEventListener("click", function () {
  8531. if (a.parentElement) {
  8532. a.parentElement.removeChild(a);
  8533. }
  8534. });
  8535. a.click();
  8536. }
  8537. else {
  8538. var newWindow = window.open("");
  8539. if (!newWindow)
  8540. return;
  8541. var img = newWindow.document.createElement("img");
  8542. img.onload = function () {
  8543. // no longer need to read the blob so it's revoked
  8544. URL.revokeObjectURL(url);
  8545. };
  8546. img.src = url;
  8547. newWindow.document.body.appendChild(img);
  8548. }
  8549. });
  8550. }
  8551. };
  8552. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8553. if (mimeType === void 0) { mimeType = "image/png"; }
  8554. var width;
  8555. var height;
  8556. // If a precision value is specified
  8557. if (size.precision) {
  8558. width = Math.round(engine.getRenderWidth() * size.precision);
  8559. height = Math.round(width / engine.getAspectRatio(camera));
  8560. }
  8561. else if (size.width && size.height) {
  8562. width = size.width;
  8563. height = size.height;
  8564. }
  8565. else if (size.width && !size.height) {
  8566. width = size.width;
  8567. height = Math.round(width / engine.getAspectRatio(camera));
  8568. }
  8569. else if (size.height && !size.width) {
  8570. height = size.height;
  8571. width = Math.round(height * engine.getAspectRatio(camera));
  8572. }
  8573. else if (!isNaN(size)) {
  8574. height = size;
  8575. width = size;
  8576. }
  8577. else {
  8578. Tools.Error("Invalid 'size' parameter !");
  8579. return;
  8580. }
  8581. if (!screenshotCanvas) {
  8582. screenshotCanvas = document.createElement('canvas');
  8583. }
  8584. screenshotCanvas.width = width;
  8585. screenshotCanvas.height = height;
  8586. var renderContext = screenshotCanvas.getContext("2d");
  8587. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8588. var newWidth = width;
  8589. var newHeight = newWidth / ratio;
  8590. if (newHeight > height) {
  8591. newHeight = height;
  8592. newWidth = newHeight * ratio;
  8593. }
  8594. var offsetX = Math.max(0, width - newWidth) / 2;
  8595. var offsetY = Math.max(0, height - newHeight) / 2;
  8596. var renderingCanvas = engine.getRenderingCanvas();
  8597. if (renderContext && renderingCanvas) {
  8598. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8599. }
  8600. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8601. };
  8602. /**
  8603. * Generates an image screenshot from the specified camera.
  8604. *
  8605. * @param engine The engine to use for rendering
  8606. * @param camera The camera to use for rendering
  8607. * @param size This parameter can be set to a single number or to an object with the
  8608. * following (optional) properties: precision, width, height. If a single number is passed,
  8609. * it will be used for both width and height. If an object is passed, the screenshot size
  8610. * will be derived from the parameters. The precision property is a multiplier allowing
  8611. * rendering at a higher or lower resolution.
  8612. * @param successCallback The callback receives a single parameter which contains the
  8613. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8614. * src parameter of an <img> to display it.
  8615. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8616. * Check your browser for supported MIME types.
  8617. * @param samples Texture samples (default: 1)
  8618. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8619. * @param fileName A name for for the downloaded file.
  8620. * @constructor
  8621. */
  8622. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8623. if (mimeType === void 0) { mimeType = "image/png"; }
  8624. if (samples === void 0) { samples = 1; }
  8625. if (antialiasing === void 0) { antialiasing = false; }
  8626. var width;
  8627. var height;
  8628. //If a precision value is specified
  8629. if (size.precision) {
  8630. width = Math.round(engine.getRenderWidth() * size.precision);
  8631. height = Math.round(width / engine.getAspectRatio(camera));
  8632. size = { width: width, height: height };
  8633. }
  8634. else if (size.width && size.height) {
  8635. width = size.width;
  8636. height = size.height;
  8637. }
  8638. else if (size.width && !size.height) {
  8639. width = size.width;
  8640. height = Math.round(width / engine.getAspectRatio(camera));
  8641. size = { width: width, height: height };
  8642. }
  8643. else if (size.height && !size.width) {
  8644. height = size.height;
  8645. width = Math.round(height * engine.getAspectRatio(camera));
  8646. size = { width: width, height: height };
  8647. }
  8648. else if (!isNaN(size)) {
  8649. height = size;
  8650. width = size;
  8651. }
  8652. else {
  8653. Tools.Error("Invalid 'size' parameter !");
  8654. return;
  8655. }
  8656. var scene = camera.getScene();
  8657. var previousCamera = null;
  8658. if (scene.activeCamera !== camera) {
  8659. previousCamera = scene.activeCamera;
  8660. scene.activeCamera = camera;
  8661. }
  8662. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8663. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8664. texture.renderList = null;
  8665. texture.samples = samples;
  8666. if (antialiasing) {
  8667. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8668. }
  8669. texture.onAfterRenderObservable.add(function () {
  8670. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8671. });
  8672. scene.incrementRenderId();
  8673. scene.resetCachedMaterial();
  8674. texture.render(true);
  8675. texture.dispose();
  8676. if (previousCamera) {
  8677. scene.activeCamera = previousCamera;
  8678. }
  8679. camera.getProjectionMatrix(true); // Force cache refresh;
  8680. };
  8681. // XHR response validator for local file scenario
  8682. Tools.ValidateXHRData = function (xhr, dataType) {
  8683. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8684. if (dataType === void 0) { dataType = 7; }
  8685. try {
  8686. if (dataType & 1) {
  8687. if (xhr.responseText && xhr.responseText.length > 0) {
  8688. return true;
  8689. }
  8690. else if (dataType === 1) {
  8691. return false;
  8692. }
  8693. }
  8694. if (dataType & 2) {
  8695. // Check header width and height since there is no "TGA" magic number
  8696. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8697. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8698. return true;
  8699. }
  8700. else if (dataType === 2) {
  8701. return false;
  8702. }
  8703. }
  8704. if (dataType & 4) {
  8705. // Check for the "DDS" magic number
  8706. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8707. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8708. return true;
  8709. }
  8710. else {
  8711. return false;
  8712. }
  8713. }
  8714. }
  8715. catch (e) {
  8716. // Global protection
  8717. }
  8718. return false;
  8719. };
  8720. /**
  8721. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8722. * Be aware Math.random() could cause collisions, but:
  8723. * "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"
  8724. */
  8725. Tools.RandomId = function () {
  8726. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8727. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8728. return v.toString(16);
  8729. });
  8730. };
  8731. /**
  8732. * Test if the given uri is a base64 string.
  8733. * @param uri The uri to test
  8734. * @return True if the uri is a base64 string or false otherwise.
  8735. */
  8736. Tools.IsBase64 = function (uri) {
  8737. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8738. };
  8739. /**
  8740. * Decode the given base64 uri.
  8741. * @param uri The uri to decode
  8742. * @return The decoded base64 data.
  8743. */
  8744. Tools.DecodeBase64 = function (uri) {
  8745. var decodedString = atob(uri.split(",")[1]);
  8746. var bufferLength = decodedString.length;
  8747. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8748. for (var i = 0; i < bufferLength; i++) {
  8749. bufferView[i] = decodedString.charCodeAt(i);
  8750. }
  8751. return bufferView.buffer;
  8752. };
  8753. Object.defineProperty(Tools, "NoneLogLevel", {
  8754. get: function () {
  8755. return Tools._NoneLogLevel;
  8756. },
  8757. enumerable: true,
  8758. configurable: true
  8759. });
  8760. Object.defineProperty(Tools, "MessageLogLevel", {
  8761. get: function () {
  8762. return Tools._MessageLogLevel;
  8763. },
  8764. enumerable: true,
  8765. configurable: true
  8766. });
  8767. Object.defineProperty(Tools, "WarningLogLevel", {
  8768. get: function () {
  8769. return Tools._WarningLogLevel;
  8770. },
  8771. enumerable: true,
  8772. configurable: true
  8773. });
  8774. Object.defineProperty(Tools, "ErrorLogLevel", {
  8775. get: function () {
  8776. return Tools._ErrorLogLevel;
  8777. },
  8778. enumerable: true,
  8779. configurable: true
  8780. });
  8781. Object.defineProperty(Tools, "AllLogLevel", {
  8782. get: function () {
  8783. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8784. },
  8785. enumerable: true,
  8786. configurable: true
  8787. });
  8788. Tools._AddLogEntry = function (entry) {
  8789. Tools._LogCache = entry + Tools._LogCache;
  8790. if (Tools.OnNewCacheEntry) {
  8791. Tools.OnNewCacheEntry(entry);
  8792. }
  8793. };
  8794. Tools._FormatMessage = function (message) {
  8795. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8796. var date = new Date();
  8797. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8798. };
  8799. Tools._LogDisabled = function (message) {
  8800. // nothing to do
  8801. };
  8802. Tools._LogEnabled = function (message) {
  8803. var formattedMessage = Tools._FormatMessage(message);
  8804. console.log("BJS - " + formattedMessage);
  8805. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8806. Tools._AddLogEntry(entry);
  8807. };
  8808. Tools._WarnDisabled = function (message) {
  8809. // nothing to do
  8810. };
  8811. Tools._WarnEnabled = function (message) {
  8812. var formattedMessage = Tools._FormatMessage(message);
  8813. console.warn("BJS - " + formattedMessage);
  8814. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8815. Tools._AddLogEntry(entry);
  8816. };
  8817. Tools._ErrorDisabled = function (message) {
  8818. // nothing to do
  8819. };
  8820. Tools._ErrorEnabled = function (message) {
  8821. Tools.errorsCount++;
  8822. var formattedMessage = Tools._FormatMessage(message);
  8823. console.error("BJS - " + formattedMessage);
  8824. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8825. Tools._AddLogEntry(entry);
  8826. };
  8827. Object.defineProperty(Tools, "LogCache", {
  8828. get: function () {
  8829. return Tools._LogCache;
  8830. },
  8831. enumerable: true,
  8832. configurable: true
  8833. });
  8834. Tools.ClearLogCache = function () {
  8835. Tools._LogCache = "";
  8836. Tools.errorsCount = 0;
  8837. };
  8838. Object.defineProperty(Tools, "LogLevels", {
  8839. set: function (level) {
  8840. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8841. Tools.Log = Tools._LogEnabled;
  8842. }
  8843. else {
  8844. Tools.Log = Tools._LogDisabled;
  8845. }
  8846. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8847. Tools.Warn = Tools._WarnEnabled;
  8848. }
  8849. else {
  8850. Tools.Warn = Tools._WarnDisabled;
  8851. }
  8852. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8853. Tools.Error = Tools._ErrorEnabled;
  8854. }
  8855. else {
  8856. Tools.Error = Tools._ErrorDisabled;
  8857. }
  8858. },
  8859. enumerable: true,
  8860. configurable: true
  8861. });
  8862. Tools.IsWindowObjectExist = function () {
  8863. return (typeof window) !== "undefined";
  8864. };
  8865. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8866. get: function () {
  8867. return Tools._PerformanceNoneLogLevel;
  8868. },
  8869. enumerable: true,
  8870. configurable: true
  8871. });
  8872. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8873. get: function () {
  8874. return Tools._PerformanceUserMarkLogLevel;
  8875. },
  8876. enumerable: true,
  8877. configurable: true
  8878. });
  8879. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8880. get: function () {
  8881. return Tools._PerformanceConsoleLogLevel;
  8882. },
  8883. enumerable: true,
  8884. configurable: true
  8885. });
  8886. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8887. set: function (level) {
  8888. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8889. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8890. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8891. return;
  8892. }
  8893. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8894. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8895. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8896. return;
  8897. }
  8898. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8899. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8900. },
  8901. enumerable: true,
  8902. configurable: true
  8903. });
  8904. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8905. };
  8906. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8907. };
  8908. Tools._StartUserMark = function (counterName, condition) {
  8909. if (condition === void 0) { condition = true; }
  8910. if (!Tools._performance) {
  8911. if (!Tools.IsWindowObjectExist()) {
  8912. return;
  8913. }
  8914. Tools._performance = window.performance;
  8915. }
  8916. if (!condition || !Tools._performance.mark) {
  8917. return;
  8918. }
  8919. Tools._performance.mark(counterName + "-Begin");
  8920. };
  8921. Tools._EndUserMark = function (counterName, condition) {
  8922. if (condition === void 0) { condition = true; }
  8923. if (!condition || !Tools._performance.mark) {
  8924. return;
  8925. }
  8926. Tools._performance.mark(counterName + "-End");
  8927. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8928. };
  8929. Tools._StartPerformanceConsole = function (counterName, condition) {
  8930. if (condition === void 0) { condition = true; }
  8931. if (!condition) {
  8932. return;
  8933. }
  8934. Tools._StartUserMark(counterName, condition);
  8935. if (console.time) {
  8936. console.time(counterName);
  8937. }
  8938. };
  8939. Tools._EndPerformanceConsole = function (counterName, condition) {
  8940. if (condition === void 0) { condition = true; }
  8941. if (!condition) {
  8942. return;
  8943. }
  8944. Tools._EndUserMark(counterName, condition);
  8945. if (console.time) {
  8946. console.timeEnd(counterName);
  8947. }
  8948. };
  8949. Object.defineProperty(Tools, "Now", {
  8950. get: function () {
  8951. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8952. return window.performance.now();
  8953. }
  8954. return new Date().getTime();
  8955. },
  8956. enumerable: true,
  8957. configurable: true
  8958. });
  8959. /**
  8960. * This method will return the name of the class used to create the instance of the given object.
  8961. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8962. * @param object the object to get the class name from
  8963. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8964. */
  8965. Tools.GetClassName = function (object, isType) {
  8966. if (isType === void 0) { isType = false; }
  8967. var name = null;
  8968. if (!isType && object.getClassName) {
  8969. name = object.getClassName();
  8970. }
  8971. else {
  8972. if (object instanceof Object) {
  8973. var classObj = isType ? object : Object.getPrototypeOf(object);
  8974. name = classObj.constructor["__bjsclassName__"];
  8975. }
  8976. if (!name) {
  8977. name = typeof object;
  8978. }
  8979. }
  8980. return name;
  8981. };
  8982. Tools.First = function (array, predicate) {
  8983. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8984. var el = array_1[_i];
  8985. if (predicate(el)) {
  8986. return el;
  8987. }
  8988. }
  8989. return null;
  8990. };
  8991. /**
  8992. * This method will return the name of the full name of the class, including its owning module (if any).
  8993. * 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).
  8994. * @param object the object to get the class name from
  8995. * @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.
  8996. */
  8997. Tools.getFullClassName = function (object, isType) {
  8998. if (isType === void 0) { isType = false; }
  8999. var className = null;
  9000. var moduleName = null;
  9001. if (!isType && object.getClassName) {
  9002. className = object.getClassName();
  9003. }
  9004. else {
  9005. if (object instanceof Object) {
  9006. var classObj = isType ? object : Object.getPrototypeOf(object);
  9007. className = classObj.constructor["__bjsclassName__"];
  9008. moduleName = classObj.constructor["__bjsmoduleName__"];
  9009. }
  9010. if (!className) {
  9011. className = typeof object;
  9012. }
  9013. }
  9014. if (!className) {
  9015. return null;
  9016. }
  9017. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9018. };
  9019. /**
  9020. * 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.
  9021. * @param array
  9022. */
  9023. Tools.arrayOrStringFeeder = function (array) {
  9024. return function (index) {
  9025. if (index >= array.length) {
  9026. return null;
  9027. }
  9028. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9029. if (val && val.getHashCode) {
  9030. val = val.getHashCode();
  9031. }
  9032. if (typeof val === "string") {
  9033. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9034. }
  9035. return val;
  9036. };
  9037. };
  9038. /**
  9039. * Compute the hashCode of a stream of number
  9040. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9041. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9042. * @return the hash code computed
  9043. */
  9044. Tools.hashCodeFromStream = function (feeder) {
  9045. // Based from here: http://stackoverflow.com/a/7616484/802124
  9046. var hash = 0;
  9047. var index = 0;
  9048. var chr = feeder(index++);
  9049. while (chr != null) {
  9050. hash = ((hash << 5) - hash) + chr;
  9051. hash |= 0; // Convert to 32bit integer
  9052. chr = feeder(index++);
  9053. }
  9054. return hash;
  9055. };
  9056. /**
  9057. * Returns a promise that resolves after the given amount of time.
  9058. * @param delay Number of milliseconds to delay
  9059. * @returns Promise that resolves after the given amount of time
  9060. */
  9061. Tools.DelayAsync = function (delay) {
  9062. return new Promise(function (resolve) {
  9063. setTimeout(function () {
  9064. resolve();
  9065. }, delay);
  9066. });
  9067. };
  9068. Tools.BaseUrl = "";
  9069. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9070. /**
  9071. * Default behaviour for cors in the application.
  9072. * It can be a string if the expected behavior is identical in the entire app.
  9073. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9074. */
  9075. Tools.CorsBehavior = "anonymous";
  9076. Tools.UseFallbackTexture = true;
  9077. /**
  9078. * Use this object to register external classes like custom textures or material
  9079. * to allow the laoders to instantiate them
  9080. */
  9081. Tools.RegisteredExternalClasses = {};
  9082. // Used in case of a texture loading problem
  9083. 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";
  9084. Tools.PreprocessUrl = function (url) {
  9085. return url;
  9086. };
  9087. // Logs
  9088. Tools._NoneLogLevel = 0;
  9089. Tools._MessageLogLevel = 1;
  9090. Tools._WarningLogLevel = 2;
  9091. Tools._ErrorLogLevel = 4;
  9092. Tools._LogCache = "";
  9093. Tools.errorsCount = 0;
  9094. Tools.Log = Tools._LogEnabled;
  9095. Tools.Warn = Tools._WarnEnabled;
  9096. Tools.Error = Tools._ErrorEnabled;
  9097. // Performances
  9098. Tools._PerformanceNoneLogLevel = 0;
  9099. Tools._PerformanceUserMarkLogLevel = 1;
  9100. Tools._PerformanceConsoleLogLevel = 2;
  9101. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9102. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9103. return Tools;
  9104. }());
  9105. BABYLON.Tools = Tools;
  9106. /**
  9107. * This class is used to track a performance counter which is number based.
  9108. * The user has access to many properties which give statistics of different nature
  9109. *
  9110. * The implementer can track two kinds of Performance Counter: time and count
  9111. * 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.
  9112. * 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.
  9113. */
  9114. var PerfCounter = /** @class */ (function () {
  9115. function PerfCounter() {
  9116. this._startMonitoringTime = 0;
  9117. this._min = 0;
  9118. this._max = 0;
  9119. this._average = 0;
  9120. this._lastSecAverage = 0;
  9121. this._current = 0;
  9122. this._totalValueCount = 0;
  9123. this._totalAccumulated = 0;
  9124. this._lastSecAccumulated = 0;
  9125. this._lastSecTime = 0;
  9126. this._lastSecValueCount = 0;
  9127. }
  9128. Object.defineProperty(PerfCounter.prototype, "min", {
  9129. /**
  9130. * Returns the smallest value ever
  9131. */
  9132. get: function () {
  9133. return this._min;
  9134. },
  9135. enumerable: true,
  9136. configurable: true
  9137. });
  9138. Object.defineProperty(PerfCounter.prototype, "max", {
  9139. /**
  9140. * Returns the biggest value ever
  9141. */
  9142. get: function () {
  9143. return this._max;
  9144. },
  9145. enumerable: true,
  9146. configurable: true
  9147. });
  9148. Object.defineProperty(PerfCounter.prototype, "average", {
  9149. /**
  9150. * Returns the average value since the performance counter is running
  9151. */
  9152. get: function () {
  9153. return this._average;
  9154. },
  9155. enumerable: true,
  9156. configurable: true
  9157. });
  9158. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9159. /**
  9160. * Returns the average value of the last second the counter was monitored
  9161. */
  9162. get: function () {
  9163. return this._lastSecAverage;
  9164. },
  9165. enumerable: true,
  9166. configurable: true
  9167. });
  9168. Object.defineProperty(PerfCounter.prototype, "current", {
  9169. /**
  9170. * Returns the current value
  9171. */
  9172. get: function () {
  9173. return this._current;
  9174. },
  9175. enumerable: true,
  9176. configurable: true
  9177. });
  9178. Object.defineProperty(PerfCounter.prototype, "total", {
  9179. get: function () {
  9180. return this._totalAccumulated;
  9181. },
  9182. enumerable: true,
  9183. configurable: true
  9184. });
  9185. Object.defineProperty(PerfCounter.prototype, "count", {
  9186. get: function () {
  9187. return this._totalValueCount;
  9188. },
  9189. enumerable: true,
  9190. configurable: true
  9191. });
  9192. /**
  9193. * Call this method to start monitoring a new frame.
  9194. * 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.
  9195. */
  9196. PerfCounter.prototype.fetchNewFrame = function () {
  9197. this._totalValueCount++;
  9198. this._current = 0;
  9199. this._lastSecValueCount++;
  9200. };
  9201. /**
  9202. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9203. * @param newCount the count value to add to the monitored count
  9204. * @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.
  9205. */
  9206. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9207. if (!PerfCounter.Enabled) {
  9208. return;
  9209. }
  9210. this._current += newCount;
  9211. if (fetchResult) {
  9212. this._fetchResult();
  9213. }
  9214. };
  9215. /**
  9216. * Start monitoring this performance counter
  9217. */
  9218. PerfCounter.prototype.beginMonitoring = function () {
  9219. if (!PerfCounter.Enabled) {
  9220. return;
  9221. }
  9222. this._startMonitoringTime = Tools.Now;
  9223. };
  9224. /**
  9225. * Compute the time lapsed since the previous beginMonitoring() call.
  9226. * @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
  9227. */
  9228. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9229. if (newFrame === void 0) { newFrame = true; }
  9230. if (!PerfCounter.Enabled) {
  9231. return;
  9232. }
  9233. if (newFrame) {
  9234. this.fetchNewFrame();
  9235. }
  9236. var currentTime = Tools.Now;
  9237. this._current = currentTime - this._startMonitoringTime;
  9238. if (newFrame) {
  9239. this._fetchResult();
  9240. }
  9241. };
  9242. PerfCounter.prototype._fetchResult = function () {
  9243. this._totalAccumulated += this._current;
  9244. this._lastSecAccumulated += this._current;
  9245. // Min/Max update
  9246. this._min = Math.min(this._min, this._current);
  9247. this._max = Math.max(this._max, this._current);
  9248. this._average = this._totalAccumulated / this._totalValueCount;
  9249. // Reset last sec?
  9250. var now = Tools.Now;
  9251. if ((now - this._lastSecTime) > 1000) {
  9252. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9253. this._lastSecTime = now;
  9254. this._lastSecAccumulated = 0;
  9255. this._lastSecValueCount = 0;
  9256. }
  9257. };
  9258. PerfCounter.Enabled = true;
  9259. return PerfCounter;
  9260. }());
  9261. BABYLON.PerfCounter = PerfCounter;
  9262. /**
  9263. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9264. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9265. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9266. * @param name The name of the class, case should be preserved
  9267. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9268. */
  9269. function className(name, module) {
  9270. return function (target) {
  9271. target["__bjsclassName__"] = name;
  9272. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9273. };
  9274. }
  9275. BABYLON.className = className;
  9276. /**
  9277. * An implementation of a loop for asynchronous functions.
  9278. */
  9279. var AsyncLoop = /** @class */ (function () {
  9280. /**
  9281. * Constroctor.
  9282. * @param iterations the number of iterations.
  9283. * @param _fn the function to run each iteration
  9284. * @param _successCallback the callback that will be called upon succesful execution
  9285. * @param offset starting offset.
  9286. */
  9287. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9288. if (offset === void 0) { offset = 0; }
  9289. this.iterations = iterations;
  9290. this._fn = _fn;
  9291. this._successCallback = _successCallback;
  9292. this.index = offset - 1;
  9293. this._done = false;
  9294. }
  9295. /**
  9296. * Execute the next iteration. Must be called after the last iteration was finished.
  9297. */
  9298. AsyncLoop.prototype.executeNext = function () {
  9299. if (!this._done) {
  9300. if (this.index + 1 < this.iterations) {
  9301. ++this.index;
  9302. this._fn(this);
  9303. }
  9304. else {
  9305. this.breakLoop();
  9306. }
  9307. }
  9308. };
  9309. /**
  9310. * Break the loop and run the success callback.
  9311. */
  9312. AsyncLoop.prototype.breakLoop = function () {
  9313. this._done = true;
  9314. this._successCallback();
  9315. };
  9316. /**
  9317. * Helper function
  9318. */
  9319. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9320. if (offset === void 0) { offset = 0; }
  9321. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9322. loop.executeNext();
  9323. return loop;
  9324. };
  9325. /**
  9326. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9327. * @param iterations total number of iterations
  9328. * @param syncedIterations number of synchronous iterations in each async iteration.
  9329. * @param fn the function to call each iteration.
  9330. * @param callback a success call back that will be called when iterating stops.
  9331. * @param breakFunction a break condition (optional)
  9332. * @param timeout timeout settings for the setTimeout function. default - 0.
  9333. * @constructor
  9334. */
  9335. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9336. if (timeout === void 0) { timeout = 0; }
  9337. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9338. if (breakFunction && breakFunction())
  9339. loop.breakLoop();
  9340. else {
  9341. setTimeout(function () {
  9342. for (var i = 0; i < syncedIterations; ++i) {
  9343. var iteration = (loop.index * syncedIterations) + i;
  9344. if (iteration >= iterations)
  9345. break;
  9346. fn(iteration);
  9347. if (breakFunction && breakFunction()) {
  9348. loop.breakLoop();
  9349. break;
  9350. }
  9351. }
  9352. loop.executeNext();
  9353. }, timeout);
  9354. }
  9355. }, callback);
  9356. };
  9357. return AsyncLoop;
  9358. }());
  9359. BABYLON.AsyncLoop = AsyncLoop;
  9360. })(BABYLON || (BABYLON = {}));
  9361. //# sourceMappingURL=babylon.tools.js.map
  9362. var BABYLON;
  9363. (function (BABYLON) {
  9364. var PromiseStates;
  9365. (function (PromiseStates) {
  9366. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9367. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9368. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9369. })(PromiseStates || (PromiseStates = {}));
  9370. var FulFillmentAgregator = /** @class */ (function () {
  9371. function FulFillmentAgregator() {
  9372. this.count = 0;
  9373. this.target = 0;
  9374. this.results = [];
  9375. }
  9376. return FulFillmentAgregator;
  9377. }());
  9378. var InternalPromise = /** @class */ (function () {
  9379. function InternalPromise(resolver) {
  9380. var _this = this;
  9381. this._state = PromiseStates.Pending;
  9382. this._children = new Array();
  9383. this._rejectWasConsumed = false;
  9384. if (!resolver) {
  9385. return;
  9386. }
  9387. try {
  9388. resolver(function (value) {
  9389. _this._resolve(value);
  9390. }, function (reason) {
  9391. _this._reject(reason);
  9392. });
  9393. }
  9394. catch (e) {
  9395. this._reject(e);
  9396. }
  9397. }
  9398. InternalPromise.prototype.catch = function (onRejected) {
  9399. return this.then(undefined, onRejected);
  9400. };
  9401. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9402. var _this = this;
  9403. var newPromise = new InternalPromise();
  9404. newPromise._onFulfilled = onFulfilled;
  9405. newPromise._onRejected = onRejected;
  9406. // Composition
  9407. this._children.push(newPromise);
  9408. if (this._state !== PromiseStates.Pending) {
  9409. BABYLON.Tools.SetImmediate(function () {
  9410. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9411. var returnedValue = newPromise._resolve(_this._result);
  9412. if (returnedValue !== undefined && returnedValue !== null) {
  9413. if (returnedValue._state !== undefined) {
  9414. var returnedPromise = returnedValue;
  9415. newPromise._children.push(returnedPromise);
  9416. newPromise = returnedPromise;
  9417. }
  9418. else {
  9419. newPromise._result = returnedValue;
  9420. }
  9421. }
  9422. }
  9423. else {
  9424. newPromise._reject(_this._reason);
  9425. }
  9426. });
  9427. }
  9428. return newPromise;
  9429. };
  9430. InternalPromise.prototype._moveChildren = function (children) {
  9431. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9432. if (this._state === PromiseStates.Fulfilled) {
  9433. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9434. var child = _b[_i];
  9435. child._resolve(this._result);
  9436. }
  9437. }
  9438. else if (this._state === PromiseStates.Rejected) {
  9439. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9440. var child = _d[_c];
  9441. child._reject(this._reason);
  9442. }
  9443. }
  9444. var _a;
  9445. };
  9446. InternalPromise.prototype._resolve = function (value) {
  9447. try {
  9448. this._state = PromiseStates.Fulfilled;
  9449. this._result = value;
  9450. var returnedValue = null;
  9451. if (this._onFulfilled) {
  9452. returnedValue = this._onFulfilled(value);
  9453. }
  9454. if (returnedValue !== undefined && returnedValue !== null) {
  9455. if (returnedValue._state !== undefined) {
  9456. // Transmit children
  9457. var returnedPromise = returnedValue;
  9458. returnedPromise._moveChildren(this._children);
  9459. }
  9460. else {
  9461. value = returnedValue;
  9462. }
  9463. }
  9464. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9465. var child = _a[_i];
  9466. child._resolve(value);
  9467. }
  9468. this._children.length = 0;
  9469. delete this._onFulfilled;
  9470. delete this._onRejected;
  9471. return returnedValue;
  9472. }
  9473. catch (e) {
  9474. this._reject(e, true);
  9475. }
  9476. return null;
  9477. };
  9478. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9479. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9480. this._state = PromiseStates.Rejected;
  9481. this._reason = reason;
  9482. if (this._onRejected && !onLocalThrow) {
  9483. try {
  9484. this._onRejected(reason);
  9485. this._rejectWasConsumed = true;
  9486. }
  9487. catch (e) {
  9488. reason = e;
  9489. }
  9490. }
  9491. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9492. var child = _a[_i];
  9493. if (this._rejectWasConsumed) {
  9494. child._resolve(null);
  9495. }
  9496. else {
  9497. child._reject(reason);
  9498. }
  9499. }
  9500. this._children.length = 0;
  9501. delete this._onFulfilled;
  9502. delete this._onRejected;
  9503. };
  9504. InternalPromise.resolve = function (value) {
  9505. var newPromise = new InternalPromise();
  9506. newPromise._resolve(value);
  9507. return newPromise;
  9508. };
  9509. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9510. promise.then(function (value) {
  9511. agregator.results[index] = value;
  9512. agregator.count++;
  9513. if (agregator.count === agregator.target) {
  9514. agregator.rootPromise._resolve(agregator.results);
  9515. }
  9516. return null;
  9517. }, function (reason) {
  9518. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9519. agregator.rootPromise._reject(reason);
  9520. }
  9521. });
  9522. };
  9523. InternalPromise.all = function (promises) {
  9524. var newPromise = new InternalPromise();
  9525. var agregator = new FulFillmentAgregator();
  9526. agregator.target = promises.length;
  9527. agregator.rootPromise = newPromise;
  9528. if (promises.length) {
  9529. for (var index = 0; index < promises.length; index++) {
  9530. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9531. }
  9532. }
  9533. else {
  9534. newPromise._resolve([]);
  9535. }
  9536. return newPromise;
  9537. };
  9538. InternalPromise.race = function (promises) {
  9539. var newPromise = new InternalPromise();
  9540. if (promises.length) {
  9541. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9542. var promise = promises_1[_i];
  9543. promise.then(function (value) {
  9544. if (newPromise) {
  9545. newPromise._resolve(value);
  9546. newPromise = null;
  9547. }
  9548. return null;
  9549. }, function (reason) {
  9550. if (newPromise) {
  9551. newPromise._reject(reason);
  9552. newPromise = null;
  9553. }
  9554. });
  9555. }
  9556. }
  9557. return newPromise;
  9558. };
  9559. return InternalPromise;
  9560. }());
  9561. /**
  9562. * Helper class that provides a small promise polyfill
  9563. */
  9564. var PromisePolyfill = /** @class */ (function () {
  9565. function PromisePolyfill() {
  9566. }
  9567. /**
  9568. * Static function used to check if the polyfill is required
  9569. * If this is the case then the function will inject the polyfill to window.Promise
  9570. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9571. */
  9572. PromisePolyfill.Apply = function (force) {
  9573. if (force === void 0) { force = false; }
  9574. if (force || typeof Promise === 'undefined') {
  9575. var root = window;
  9576. root.Promise = InternalPromise;
  9577. }
  9578. };
  9579. return PromisePolyfill;
  9580. }());
  9581. BABYLON.PromisePolyfill = PromisePolyfill;
  9582. })(BABYLON || (BABYLON = {}));
  9583. //# sourceMappingURL=babylon.promise.js.map
  9584. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9585. var BABYLON;
  9586. (function (BABYLON) {
  9587. /**
  9588. * Helper class to push actions to a pool of workers.
  9589. */
  9590. var WorkerPool = /** @class */ (function () {
  9591. /**
  9592. * Constructor
  9593. * @param workers Array of workers to use for actions
  9594. */
  9595. function WorkerPool(workers) {
  9596. this._pendingActions = new Array();
  9597. this._workerInfos = workers.map(function (worker) { return ({
  9598. worker: worker,
  9599. active: false
  9600. }); });
  9601. }
  9602. /**
  9603. * Terminates all workers and clears any pending actions.
  9604. */
  9605. WorkerPool.prototype.dispose = function () {
  9606. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9607. var workerInfo = _a[_i];
  9608. workerInfo.worker.terminate();
  9609. }
  9610. delete this._workerInfos;
  9611. delete this._pendingActions;
  9612. };
  9613. /**
  9614. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9615. * pended until a worker has completed its action.
  9616. * @param action The action to perform. Call onComplete when the action is complete.
  9617. */
  9618. WorkerPool.prototype.push = function (action) {
  9619. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9620. var workerInfo = _a[_i];
  9621. if (!workerInfo.active) {
  9622. this._execute(workerInfo, action);
  9623. return;
  9624. }
  9625. }
  9626. this._pendingActions.push(action);
  9627. };
  9628. WorkerPool.prototype._execute = function (workerInfo, action) {
  9629. var _this = this;
  9630. workerInfo.active = true;
  9631. action(workerInfo.worker, function () {
  9632. workerInfo.active = false;
  9633. var nextAction = _this._pendingActions.shift();
  9634. if (nextAction) {
  9635. _this._execute(workerInfo, nextAction);
  9636. }
  9637. });
  9638. };
  9639. return WorkerPool;
  9640. }());
  9641. BABYLON.WorkerPool = WorkerPool;
  9642. })(BABYLON || (BABYLON = {}));
  9643. //# sourceMappingURL=babylon.workerPool.js.map
  9644. var BABYLON;
  9645. (function (BABYLON) {
  9646. var _AlphaState = /** @class */ (function () {
  9647. /**
  9648. * Initializes the state.
  9649. */
  9650. function _AlphaState() {
  9651. this._isAlphaBlendDirty = false;
  9652. this._isBlendFunctionParametersDirty = false;
  9653. this._isBlendEquationParametersDirty = false;
  9654. this._isBlendConstantsDirty = false;
  9655. this._alphaBlend = false;
  9656. this._blendFunctionParameters = new Array(4);
  9657. this._blendEquationParameters = new Array(2);
  9658. this._blendConstants = new Array(4);
  9659. this.reset();
  9660. }
  9661. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9662. get: function () {
  9663. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9664. },
  9665. enumerable: true,
  9666. configurable: true
  9667. });
  9668. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9669. get: function () {
  9670. return this._alphaBlend;
  9671. },
  9672. set: function (value) {
  9673. if (this._alphaBlend === value) {
  9674. return;
  9675. }
  9676. this._alphaBlend = value;
  9677. this._isAlphaBlendDirty = true;
  9678. },
  9679. enumerable: true,
  9680. configurable: true
  9681. });
  9682. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9683. if (this._blendConstants[0] === r &&
  9684. this._blendConstants[1] === g &&
  9685. this._blendConstants[2] === b &&
  9686. this._blendConstants[3] === a) {
  9687. return;
  9688. }
  9689. this._blendConstants[0] = r;
  9690. this._blendConstants[1] = g;
  9691. this._blendConstants[2] = b;
  9692. this._blendConstants[3] = a;
  9693. this._isBlendConstantsDirty = true;
  9694. };
  9695. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9696. if (this._blendFunctionParameters[0] === value0 &&
  9697. this._blendFunctionParameters[1] === value1 &&
  9698. this._blendFunctionParameters[2] === value2 &&
  9699. this._blendFunctionParameters[3] === value3) {
  9700. return;
  9701. }
  9702. this._blendFunctionParameters[0] = value0;
  9703. this._blendFunctionParameters[1] = value1;
  9704. this._blendFunctionParameters[2] = value2;
  9705. this._blendFunctionParameters[3] = value3;
  9706. this._isBlendFunctionParametersDirty = true;
  9707. };
  9708. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9709. if (this._blendEquationParameters[0] === rgb &&
  9710. this._blendEquationParameters[1] === alpha) {
  9711. return;
  9712. }
  9713. this._blendEquationParameters[0] = rgb;
  9714. this._blendEquationParameters[1] = alpha;
  9715. this._isBlendEquationParametersDirty = true;
  9716. };
  9717. _AlphaState.prototype.reset = function () {
  9718. this._alphaBlend = false;
  9719. this._blendFunctionParameters[0] = null;
  9720. this._blendFunctionParameters[1] = null;
  9721. this._blendFunctionParameters[2] = null;
  9722. this._blendFunctionParameters[3] = null;
  9723. this._blendEquationParameters[0] = null;
  9724. this._blendEquationParameters[1] = null;
  9725. this._blendConstants[0] = null;
  9726. this._blendConstants[1] = null;
  9727. this._blendConstants[2] = null;
  9728. this._blendConstants[3] = null;
  9729. this._isAlphaBlendDirty = true;
  9730. this._isBlendFunctionParametersDirty = false;
  9731. this._isBlendEquationParametersDirty = false;
  9732. this._isBlendConstantsDirty = false;
  9733. };
  9734. _AlphaState.prototype.apply = function (gl) {
  9735. if (!this.isDirty) {
  9736. return;
  9737. }
  9738. // Alpha blend
  9739. if (this._isAlphaBlendDirty) {
  9740. if (this._alphaBlend) {
  9741. gl.enable(gl.BLEND);
  9742. }
  9743. else {
  9744. gl.disable(gl.BLEND);
  9745. }
  9746. this._isAlphaBlendDirty = false;
  9747. }
  9748. // Alpha function
  9749. if (this._isBlendFunctionParametersDirty) {
  9750. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9751. this._isBlendFunctionParametersDirty = false;
  9752. }
  9753. // Alpha equation
  9754. if (this._isBlendEquationParametersDirty) {
  9755. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9756. this._isBlendEquationParametersDirty = false;
  9757. }
  9758. // Constants
  9759. if (this._isBlendConstantsDirty) {
  9760. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9761. this._isBlendConstantsDirty = false;
  9762. }
  9763. };
  9764. return _AlphaState;
  9765. }());
  9766. BABYLON._AlphaState = _AlphaState;
  9767. })(BABYLON || (BABYLON = {}));
  9768. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9769. var BABYLON;
  9770. (function (BABYLON) {
  9771. var _DepthCullingState = /** @class */ (function () {
  9772. /**
  9773. * Initializes the state.
  9774. */
  9775. function _DepthCullingState() {
  9776. this._isDepthTestDirty = false;
  9777. this._isDepthMaskDirty = false;
  9778. this._isDepthFuncDirty = false;
  9779. this._isCullFaceDirty = false;
  9780. this._isCullDirty = false;
  9781. this._isZOffsetDirty = false;
  9782. this._isFrontFaceDirty = false;
  9783. this.reset();
  9784. }
  9785. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9786. get: function () {
  9787. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9788. },
  9789. enumerable: true,
  9790. configurable: true
  9791. });
  9792. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9793. get: function () {
  9794. return this._zOffset;
  9795. },
  9796. set: function (value) {
  9797. if (this._zOffset === value) {
  9798. return;
  9799. }
  9800. this._zOffset = value;
  9801. this._isZOffsetDirty = true;
  9802. },
  9803. enumerable: true,
  9804. configurable: true
  9805. });
  9806. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9807. get: function () {
  9808. return this._cullFace;
  9809. },
  9810. set: function (value) {
  9811. if (this._cullFace === value) {
  9812. return;
  9813. }
  9814. this._cullFace = value;
  9815. this._isCullFaceDirty = true;
  9816. },
  9817. enumerable: true,
  9818. configurable: true
  9819. });
  9820. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9821. get: function () {
  9822. return this._cull;
  9823. },
  9824. set: function (value) {
  9825. if (this._cull === value) {
  9826. return;
  9827. }
  9828. this._cull = value;
  9829. this._isCullDirty = true;
  9830. },
  9831. enumerable: true,
  9832. configurable: true
  9833. });
  9834. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9835. get: function () {
  9836. return this._depthFunc;
  9837. },
  9838. set: function (value) {
  9839. if (this._depthFunc === value) {
  9840. return;
  9841. }
  9842. this._depthFunc = value;
  9843. this._isDepthFuncDirty = true;
  9844. },
  9845. enumerable: true,
  9846. configurable: true
  9847. });
  9848. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9849. get: function () {
  9850. return this._depthMask;
  9851. },
  9852. set: function (value) {
  9853. if (this._depthMask === value) {
  9854. return;
  9855. }
  9856. this._depthMask = value;
  9857. this._isDepthMaskDirty = true;
  9858. },
  9859. enumerable: true,
  9860. configurable: true
  9861. });
  9862. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9863. get: function () {
  9864. return this._depthTest;
  9865. },
  9866. set: function (value) {
  9867. if (this._depthTest === value) {
  9868. return;
  9869. }
  9870. this._depthTest = value;
  9871. this._isDepthTestDirty = true;
  9872. },
  9873. enumerable: true,
  9874. configurable: true
  9875. });
  9876. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9877. get: function () {
  9878. return this._frontFace;
  9879. },
  9880. set: function (value) {
  9881. if (this._frontFace === value) {
  9882. return;
  9883. }
  9884. this._frontFace = value;
  9885. this._isFrontFaceDirty = true;
  9886. },
  9887. enumerable: true,
  9888. configurable: true
  9889. });
  9890. _DepthCullingState.prototype.reset = function () {
  9891. this._depthMask = true;
  9892. this._depthTest = true;
  9893. this._depthFunc = null;
  9894. this._cullFace = null;
  9895. this._cull = null;
  9896. this._zOffset = 0;
  9897. this._frontFace = null;
  9898. this._isDepthTestDirty = true;
  9899. this._isDepthMaskDirty = true;
  9900. this._isDepthFuncDirty = false;
  9901. this._isCullFaceDirty = false;
  9902. this._isCullDirty = false;
  9903. this._isZOffsetDirty = false;
  9904. this._isFrontFaceDirty = false;
  9905. };
  9906. _DepthCullingState.prototype.apply = function (gl) {
  9907. if (!this.isDirty) {
  9908. return;
  9909. }
  9910. // Cull
  9911. if (this._isCullDirty) {
  9912. if (this.cull) {
  9913. gl.enable(gl.CULL_FACE);
  9914. }
  9915. else {
  9916. gl.disable(gl.CULL_FACE);
  9917. }
  9918. this._isCullDirty = false;
  9919. }
  9920. // Cull face
  9921. if (this._isCullFaceDirty) {
  9922. gl.cullFace(this.cullFace);
  9923. this._isCullFaceDirty = false;
  9924. }
  9925. // Depth mask
  9926. if (this._isDepthMaskDirty) {
  9927. gl.depthMask(this.depthMask);
  9928. this._isDepthMaskDirty = false;
  9929. }
  9930. // Depth test
  9931. if (this._isDepthTestDirty) {
  9932. if (this.depthTest) {
  9933. gl.enable(gl.DEPTH_TEST);
  9934. }
  9935. else {
  9936. gl.disable(gl.DEPTH_TEST);
  9937. }
  9938. this._isDepthTestDirty = false;
  9939. }
  9940. // Depth func
  9941. if (this._isDepthFuncDirty) {
  9942. gl.depthFunc(this.depthFunc);
  9943. this._isDepthFuncDirty = false;
  9944. }
  9945. // zOffset
  9946. if (this._isZOffsetDirty) {
  9947. if (this.zOffset) {
  9948. gl.enable(gl.POLYGON_OFFSET_FILL);
  9949. gl.polygonOffset(this.zOffset, 0);
  9950. }
  9951. else {
  9952. gl.disable(gl.POLYGON_OFFSET_FILL);
  9953. }
  9954. this._isZOffsetDirty = false;
  9955. }
  9956. // Front face
  9957. if (this._isFrontFaceDirty) {
  9958. gl.frontFace(this.frontFace);
  9959. this._isFrontFaceDirty = false;
  9960. }
  9961. };
  9962. return _DepthCullingState;
  9963. }());
  9964. BABYLON._DepthCullingState = _DepthCullingState;
  9965. })(BABYLON || (BABYLON = {}));
  9966. //# sourceMappingURL=babylon.depthCullingState.js.map
  9967. var BABYLON;
  9968. (function (BABYLON) {
  9969. var _StencilState = /** @class */ (function () {
  9970. function _StencilState() {
  9971. this._isStencilTestDirty = false;
  9972. this._isStencilMaskDirty = false;
  9973. this._isStencilFuncDirty = false;
  9974. this._isStencilOpDirty = false;
  9975. this.reset();
  9976. }
  9977. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9978. get: function () {
  9979. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9980. },
  9981. enumerable: true,
  9982. configurable: true
  9983. });
  9984. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9985. get: function () {
  9986. return this._stencilFunc;
  9987. },
  9988. set: function (value) {
  9989. if (this._stencilFunc === value) {
  9990. return;
  9991. }
  9992. this._stencilFunc = value;
  9993. this._isStencilFuncDirty = true;
  9994. },
  9995. enumerable: true,
  9996. configurable: true
  9997. });
  9998. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9999. get: function () {
  10000. return this._stencilFuncRef;
  10001. },
  10002. set: function (value) {
  10003. if (this._stencilFuncRef === value) {
  10004. return;
  10005. }
  10006. this._stencilFuncRef = value;
  10007. this._isStencilFuncDirty = true;
  10008. },
  10009. enumerable: true,
  10010. configurable: true
  10011. });
  10012. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10013. get: function () {
  10014. return this._stencilFuncMask;
  10015. },
  10016. set: function (value) {
  10017. if (this._stencilFuncMask === value) {
  10018. return;
  10019. }
  10020. this._stencilFuncMask = value;
  10021. this._isStencilFuncDirty = true;
  10022. },
  10023. enumerable: true,
  10024. configurable: true
  10025. });
  10026. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10027. get: function () {
  10028. return this._stencilOpStencilFail;
  10029. },
  10030. set: function (value) {
  10031. if (this._stencilOpStencilFail === value) {
  10032. return;
  10033. }
  10034. this._stencilOpStencilFail = value;
  10035. this._isStencilOpDirty = true;
  10036. },
  10037. enumerable: true,
  10038. configurable: true
  10039. });
  10040. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10041. get: function () {
  10042. return this._stencilOpDepthFail;
  10043. },
  10044. set: function (value) {
  10045. if (this._stencilOpDepthFail === value) {
  10046. return;
  10047. }
  10048. this._stencilOpDepthFail = value;
  10049. this._isStencilOpDirty = true;
  10050. },
  10051. enumerable: true,
  10052. configurable: true
  10053. });
  10054. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10055. get: function () {
  10056. return this._stencilOpStencilDepthPass;
  10057. },
  10058. set: function (value) {
  10059. if (this._stencilOpStencilDepthPass === value) {
  10060. return;
  10061. }
  10062. this._stencilOpStencilDepthPass = value;
  10063. this._isStencilOpDirty = true;
  10064. },
  10065. enumerable: true,
  10066. configurable: true
  10067. });
  10068. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10069. get: function () {
  10070. return this._stencilMask;
  10071. },
  10072. set: function (value) {
  10073. if (this._stencilMask === value) {
  10074. return;
  10075. }
  10076. this._stencilMask = value;
  10077. this._isStencilMaskDirty = true;
  10078. },
  10079. enumerable: true,
  10080. configurable: true
  10081. });
  10082. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10083. get: function () {
  10084. return this._stencilTest;
  10085. },
  10086. set: function (value) {
  10087. if (this._stencilTest === value) {
  10088. return;
  10089. }
  10090. this._stencilTest = value;
  10091. this._isStencilTestDirty = true;
  10092. },
  10093. enumerable: true,
  10094. configurable: true
  10095. });
  10096. _StencilState.prototype.reset = function () {
  10097. this._stencilTest = false;
  10098. this._stencilMask = 0xFF;
  10099. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10100. this._stencilFuncRef = 1;
  10101. this._stencilFuncMask = 0xFF;
  10102. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10103. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10104. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10105. this._isStencilTestDirty = true;
  10106. this._isStencilMaskDirty = true;
  10107. this._isStencilFuncDirty = true;
  10108. this._isStencilOpDirty = true;
  10109. };
  10110. _StencilState.prototype.apply = function (gl) {
  10111. if (!this.isDirty) {
  10112. return;
  10113. }
  10114. // Stencil test
  10115. if (this._isStencilTestDirty) {
  10116. if (this.stencilTest) {
  10117. gl.enable(gl.STENCIL_TEST);
  10118. }
  10119. else {
  10120. gl.disable(gl.STENCIL_TEST);
  10121. }
  10122. this._isStencilTestDirty = false;
  10123. }
  10124. // Stencil mask
  10125. if (this._isStencilMaskDirty) {
  10126. gl.stencilMask(this.stencilMask);
  10127. this._isStencilMaskDirty = false;
  10128. }
  10129. // Stencil func
  10130. if (this._isStencilFuncDirty) {
  10131. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10132. this._isStencilFuncDirty = false;
  10133. }
  10134. // Stencil op
  10135. if (this._isStencilOpDirty) {
  10136. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10137. this._isStencilOpDirty = false;
  10138. }
  10139. };
  10140. return _StencilState;
  10141. }());
  10142. BABYLON._StencilState = _StencilState;
  10143. })(BABYLON || (BABYLON = {}));
  10144. //# sourceMappingURL=babylon.stencilState.js.map
  10145. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10146. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10147. s = arguments[i];
  10148. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10149. t[p] = s[p];
  10150. }
  10151. return t;
  10152. };
  10153. var BABYLON;
  10154. (function (BABYLON) {
  10155. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10156. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10157. };
  10158. var compileRawShader = function (gl, source, type) {
  10159. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10160. gl.shaderSource(shader, source);
  10161. gl.compileShader(shader);
  10162. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10163. var log = gl.getShaderInfoLog(shader);
  10164. if (log) {
  10165. throw new Error(log);
  10166. }
  10167. }
  10168. if (!shader) {
  10169. throw new Error("Something went wrong while compile the shader.");
  10170. }
  10171. return shader;
  10172. };
  10173. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10174. var magFilter = gl.NEAREST;
  10175. var minFilter = gl.NEAREST;
  10176. switch (samplingMode) {
  10177. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10178. magFilter = gl.LINEAR;
  10179. if (generateMipMaps) {
  10180. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10181. }
  10182. else {
  10183. minFilter = gl.LINEAR;
  10184. }
  10185. break;
  10186. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10187. magFilter = gl.LINEAR;
  10188. if (generateMipMaps) {
  10189. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10190. }
  10191. else {
  10192. minFilter = gl.LINEAR;
  10193. }
  10194. break;
  10195. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10196. magFilter = gl.NEAREST;
  10197. if (generateMipMaps) {
  10198. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10199. }
  10200. else {
  10201. minFilter = gl.NEAREST;
  10202. }
  10203. break;
  10204. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10205. magFilter = gl.NEAREST;
  10206. if (generateMipMaps) {
  10207. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10208. }
  10209. else {
  10210. minFilter = gl.NEAREST;
  10211. }
  10212. break;
  10213. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10214. magFilter = gl.NEAREST;
  10215. if (generateMipMaps) {
  10216. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10217. }
  10218. else {
  10219. minFilter = gl.LINEAR;
  10220. }
  10221. break;
  10222. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10223. magFilter = gl.NEAREST;
  10224. if (generateMipMaps) {
  10225. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10226. }
  10227. else {
  10228. minFilter = gl.LINEAR;
  10229. }
  10230. break;
  10231. case BABYLON.Texture.NEAREST_LINEAR:
  10232. magFilter = gl.NEAREST;
  10233. minFilter = gl.LINEAR;
  10234. break;
  10235. case BABYLON.Texture.NEAREST_NEAREST:
  10236. magFilter = gl.NEAREST;
  10237. minFilter = gl.NEAREST;
  10238. break;
  10239. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10240. magFilter = gl.LINEAR;
  10241. if (generateMipMaps) {
  10242. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10243. }
  10244. else {
  10245. minFilter = gl.NEAREST;
  10246. }
  10247. break;
  10248. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10249. magFilter = gl.LINEAR;
  10250. if (generateMipMaps) {
  10251. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10252. }
  10253. else {
  10254. minFilter = gl.NEAREST;
  10255. }
  10256. break;
  10257. case BABYLON.Texture.LINEAR_LINEAR:
  10258. magFilter = gl.LINEAR;
  10259. minFilter = gl.LINEAR;
  10260. break;
  10261. case BABYLON.Texture.LINEAR_NEAREST:
  10262. magFilter = gl.LINEAR;
  10263. minFilter = gl.NEAREST;
  10264. break;
  10265. }
  10266. return {
  10267. min: minFilter,
  10268. mag: magFilter
  10269. };
  10270. };
  10271. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10272. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10273. var img;
  10274. var onload = function () {
  10275. loadedImages[index] = img;
  10276. loadedImages._internalCount++;
  10277. if (scene) {
  10278. scene._removePendingData(img);
  10279. }
  10280. if (loadedImages._internalCount === 6) {
  10281. onfinish(loadedImages);
  10282. }
  10283. };
  10284. var onerror = function (message, exception) {
  10285. if (scene) {
  10286. scene._removePendingData(img);
  10287. }
  10288. if (onErrorCallBack) {
  10289. onErrorCallBack(message, exception);
  10290. }
  10291. };
  10292. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10293. if (scene) {
  10294. scene._addPendingData(img);
  10295. }
  10296. };
  10297. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10298. if (onError === void 0) { onError = null; }
  10299. var loadedImages = [];
  10300. loadedImages._internalCount = 0;
  10301. for (var index = 0; index < 6; index++) {
  10302. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10303. }
  10304. };
  10305. var BufferPointer = /** @class */ (function () {
  10306. function BufferPointer() {
  10307. }
  10308. return BufferPointer;
  10309. }());
  10310. var InstancingAttributeInfo = /** @class */ (function () {
  10311. function InstancingAttributeInfo() {
  10312. }
  10313. return InstancingAttributeInfo;
  10314. }());
  10315. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10316. /**
  10317. * Define options used to create a render target texture
  10318. */
  10319. var RenderTargetCreationOptions = /** @class */ (function () {
  10320. function RenderTargetCreationOptions() {
  10321. }
  10322. return RenderTargetCreationOptions;
  10323. }());
  10324. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10325. /**
  10326. * Define options used to create a depth texture
  10327. */
  10328. var DepthTextureCreationOptions = /** @class */ (function () {
  10329. function DepthTextureCreationOptions() {
  10330. }
  10331. return DepthTextureCreationOptions;
  10332. }());
  10333. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10334. /**
  10335. * Regroup several parameters relative to the browser in use
  10336. */
  10337. var EngineCapabilities = /** @class */ (function () {
  10338. function EngineCapabilities() {
  10339. }
  10340. return EngineCapabilities;
  10341. }());
  10342. BABYLON.EngineCapabilities = EngineCapabilities;
  10343. /**
  10344. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10345. */
  10346. var Engine = /** @class */ (function () {
  10347. /**
  10348. * @constructor
  10349. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10350. * @param antialias defines enable antialiasing (default: false)
  10351. * @param options defines further options to be sent to the getContext() function
  10352. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10353. */
  10354. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10355. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10356. var _this = this;
  10357. // Public members
  10358. this.forcePOTTextures = false;
  10359. this.isFullscreen = false;
  10360. this.isPointerLock = false;
  10361. this.cullBackFaces = true;
  10362. this.renderEvenInBackground = true;
  10363. this.preventCacheWipeBetweenFrames = false;
  10364. // To enable/disable IDB support and avoid XHR on .manifest
  10365. this.enableOfflineSupport = false;
  10366. this.scenes = new Array();
  10367. this.postProcesses = new Array();
  10368. // Observables
  10369. /**
  10370. * Observable event triggered each time the rendering canvas is resized
  10371. */
  10372. this.onResizeObservable = new BABYLON.Observable();
  10373. /**
  10374. * Observable event triggered each time the canvas loses focus
  10375. */
  10376. this.onCanvasBlurObservable = new BABYLON.Observable();
  10377. /**
  10378. * Observable event triggered each time the canvas gains focus
  10379. */
  10380. this.onCanvasFocusObservable = new BABYLON.Observable();
  10381. /**
  10382. * Observable event triggered each time the canvas receives pointerout event
  10383. */
  10384. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10385. /**
  10386. * Observable event triggered before each texture is initialized
  10387. */
  10388. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10389. //WebVR
  10390. this._vrDisplay = undefined;
  10391. this._vrSupported = false;
  10392. this._vrExclusivePointerMode = false;
  10393. // Uniform buffers list
  10394. this.disableUniformBuffers = false;
  10395. this._uniformBuffers = new Array();
  10396. // Observables
  10397. /**
  10398. * Observable raised when the engine begins a new frame
  10399. */
  10400. this.onBeginFrameObservable = new BABYLON.Observable();
  10401. /**
  10402. * Observable raised when the engine ends the current frame
  10403. */
  10404. this.onEndFrameObservable = new BABYLON.Observable();
  10405. /**
  10406. * Observable raised when the engine is about to compile a shader
  10407. */
  10408. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10409. /**
  10410. * Observable raised when the engine has jsut compiled a shader
  10411. */
  10412. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10413. this._windowIsBackground = false;
  10414. this._webGLVersion = 1.0;
  10415. this._badOS = false;
  10416. this._badDesktopOS = false;
  10417. /**
  10418. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10419. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10420. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10421. */
  10422. this.disableTextureBindingOptimization = false;
  10423. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10424. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10425. this.onVRRequestPresentStart = new BABYLON.Observable();
  10426. this._colorWrite = true;
  10427. this._drawCalls = new BABYLON.PerfCounter();
  10428. this._textureCollisions = new BABYLON.PerfCounter();
  10429. this._renderingQueueLaunched = false;
  10430. this._activeRenderLoops = new Array();
  10431. // Deterministic lockstepMaxSteps
  10432. this._deterministicLockstep = false;
  10433. this._lockstepMaxSteps = 4;
  10434. // Lost context
  10435. this.onContextLostObservable = new BABYLON.Observable();
  10436. this.onContextRestoredObservable = new BABYLON.Observable();
  10437. this._contextWasLost = false;
  10438. this._doNotHandleContextLost = false;
  10439. // FPS
  10440. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10441. this._fps = 60;
  10442. this._deltaTime = 0;
  10443. /**
  10444. * Turn this value on if you want to pause FPS computation when in background
  10445. */
  10446. this.disablePerformanceMonitorInBackground = false;
  10447. // States
  10448. this._depthCullingState = new BABYLON._DepthCullingState();
  10449. this._stencilState = new BABYLON._StencilState();
  10450. this._alphaState = new BABYLON._AlphaState();
  10451. this._alphaMode = Engine.ALPHA_DISABLE;
  10452. // Cache
  10453. this._internalTexturesCache = new Array();
  10454. this._activeChannel = 0;
  10455. this._currentTextureChannel = -1;
  10456. this._boundTexturesCache = {};
  10457. this._compiledEffects = {};
  10458. this._vertexAttribArraysEnabled = [];
  10459. this._uintIndicesCurrentlySet = false;
  10460. this._currentBoundBuffer = new Array();
  10461. this._currentBufferPointers = new Array();
  10462. this._currentInstanceLocations = new Array();
  10463. this._currentInstanceBuffers = new Array();
  10464. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10465. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10466. this._vaoRecordInProgress = false;
  10467. this._mustWipeVertexAttributes = false;
  10468. this._nextFreeTextureSlots = new Array();
  10469. this._maxSimultaneousTextures = 0;
  10470. this._activeRequests = new Array();
  10471. // Hardware supported Compressed Textures
  10472. this._texturesSupported = new Array();
  10473. this._onVRFullScreenTriggered = function () {
  10474. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10475. //get the old size before we change
  10476. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10477. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10478. //get the width and height, change the render size
  10479. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10480. _this.setHardwareScalingLevel(1);
  10481. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10482. }
  10483. else {
  10484. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10485. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10486. }
  10487. };
  10488. this._boundUniforms = {};
  10489. // Register promises
  10490. BABYLON.PromisePolyfill.Apply();
  10491. var canvas = null;
  10492. Engine.Instances.push(this);
  10493. if (!canvasOrContext) {
  10494. return;
  10495. }
  10496. options = options || {};
  10497. if (canvasOrContext.getContext) {
  10498. canvas = canvasOrContext;
  10499. this._renderingCanvas = canvas;
  10500. if (antialias != null) {
  10501. options.antialias = antialias;
  10502. }
  10503. if (options.deterministicLockstep === undefined) {
  10504. options.deterministicLockstep = false;
  10505. }
  10506. if (options.lockstepMaxSteps === undefined) {
  10507. options.lockstepMaxSteps = 4;
  10508. }
  10509. if (options.preserveDrawingBuffer === undefined) {
  10510. options.preserveDrawingBuffer = false;
  10511. }
  10512. if (options.audioEngine === undefined) {
  10513. options.audioEngine = true;
  10514. }
  10515. if (options.stencil === undefined) {
  10516. options.stencil = true;
  10517. }
  10518. this._deterministicLockstep = options.deterministicLockstep;
  10519. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10520. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10521. // Exceptions
  10522. if (navigator && navigator.userAgent) {
  10523. var ua = navigator.userAgent;
  10524. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10525. var exception = _a[_i];
  10526. var key = exception.key;
  10527. var targets = exception.targets;
  10528. if (ua.indexOf(key) > -1) {
  10529. if (exception.capture && exception.captureConstraint) {
  10530. var capture = exception.capture;
  10531. var constraint = exception.captureConstraint;
  10532. var regex = new RegExp(capture);
  10533. var matches = regex.exec(ua);
  10534. if (matches && matches.length > 0) {
  10535. var capturedValue = parseInt(matches[matches.length - 1]);
  10536. if (capturedValue >= constraint) {
  10537. continue;
  10538. }
  10539. }
  10540. }
  10541. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10542. var target = targets_1[_b];
  10543. switch (target) {
  10544. case "uniformBuffer":
  10545. this.disableUniformBuffers = true;
  10546. break;
  10547. case "textureBindingOptimization":
  10548. this.disableTextureBindingOptimization = true;
  10549. break;
  10550. }
  10551. }
  10552. break;
  10553. }
  10554. }
  10555. }
  10556. // GL
  10557. if (!options.disableWebGL2Support) {
  10558. try {
  10559. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10560. if (this._gl) {
  10561. this._webGLVersion = 2.0;
  10562. }
  10563. }
  10564. catch (e) {
  10565. // Do nothing
  10566. }
  10567. }
  10568. if (!this._gl) {
  10569. if (!canvas) {
  10570. throw new Error("The provided canvas is null or undefined.");
  10571. }
  10572. try {
  10573. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10574. }
  10575. catch (e) {
  10576. throw new Error("WebGL not supported");
  10577. }
  10578. }
  10579. if (!this._gl) {
  10580. throw new Error("WebGL not supported");
  10581. }
  10582. this._onCanvasFocus = function () {
  10583. _this.onCanvasFocusObservable.notifyObservers(_this);
  10584. };
  10585. this._onCanvasBlur = function () {
  10586. _this.onCanvasBlurObservable.notifyObservers(_this);
  10587. };
  10588. canvas.addEventListener("focus", this._onCanvasFocus);
  10589. canvas.addEventListener("blur", this._onCanvasBlur);
  10590. this._onBlur = function () {
  10591. if (_this.disablePerformanceMonitorInBackground) {
  10592. _this._performanceMonitor.disable();
  10593. }
  10594. _this._windowIsBackground = true;
  10595. };
  10596. this._onFocus = function () {
  10597. if (_this.disablePerformanceMonitorInBackground) {
  10598. _this._performanceMonitor.enable();
  10599. }
  10600. _this._windowIsBackground = false;
  10601. };
  10602. this._onCanvasPointerOut = function (ev) {
  10603. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10604. };
  10605. window.addEventListener("blur", this._onBlur);
  10606. window.addEventListener("focus", this._onFocus);
  10607. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10608. // Context lost
  10609. if (!this._doNotHandleContextLost) {
  10610. this._onContextLost = function (evt) {
  10611. evt.preventDefault();
  10612. _this._contextWasLost = true;
  10613. BABYLON.Tools.Warn("WebGL context lost.");
  10614. _this.onContextLostObservable.notifyObservers(_this);
  10615. };
  10616. this._onContextRestored = function (evt) {
  10617. // Adding a timeout to avoid race condition at browser level
  10618. setTimeout(function () {
  10619. // Rebuild gl context
  10620. _this._initGLContext();
  10621. // Rebuild effects
  10622. _this._rebuildEffects();
  10623. // Rebuild textures
  10624. _this._rebuildInternalTextures();
  10625. // Rebuild buffers
  10626. _this._rebuildBuffers();
  10627. // Cache
  10628. _this.wipeCaches(true);
  10629. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10630. _this.onContextRestoredObservable.notifyObservers(_this);
  10631. _this._contextWasLost = false;
  10632. }, 0);
  10633. };
  10634. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10635. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10636. }
  10637. }
  10638. else {
  10639. this._gl = canvasOrContext;
  10640. this._renderingCanvas = this._gl.canvas;
  10641. if (this._gl.renderbufferStorageMultisample) {
  10642. this._webGLVersion = 2.0;
  10643. }
  10644. options.stencil = this._gl.getContextAttributes().stencil;
  10645. }
  10646. // Viewport
  10647. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10648. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10649. this.resize();
  10650. this._isStencilEnable = options.stencil ? true : false;
  10651. this._initGLContext();
  10652. if (canvas) {
  10653. // Fullscreen
  10654. this._onFullscreenChange = function () {
  10655. if (document.fullscreen !== undefined) {
  10656. _this.isFullscreen = document.fullscreen;
  10657. }
  10658. else if (document.mozFullScreen !== undefined) {
  10659. _this.isFullscreen = document.mozFullScreen;
  10660. }
  10661. else if (document.webkitIsFullScreen !== undefined) {
  10662. _this.isFullscreen = document.webkitIsFullScreen;
  10663. }
  10664. else if (document.msIsFullScreen !== undefined) {
  10665. _this.isFullscreen = document.msIsFullScreen;
  10666. }
  10667. // Pointer lock
  10668. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10669. canvas.requestPointerLock = canvas.requestPointerLock ||
  10670. canvas.msRequestPointerLock ||
  10671. canvas.mozRequestPointerLock ||
  10672. canvas.webkitRequestPointerLock;
  10673. if (canvas.requestPointerLock) {
  10674. canvas.requestPointerLock();
  10675. }
  10676. }
  10677. };
  10678. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10679. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10680. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10681. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10682. // Pointer lock
  10683. this._onPointerLockChange = function () {
  10684. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10685. document.webkitPointerLockElement === canvas ||
  10686. document.msPointerLockElement === canvas ||
  10687. document.pointerLockElement === canvas);
  10688. };
  10689. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10690. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10691. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10692. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10693. this._onVRDisplayPointerRestricted = function () {
  10694. if (canvas) {
  10695. canvas.requestPointerLock();
  10696. }
  10697. };
  10698. this._onVRDisplayPointerUnrestricted = function () {
  10699. document.exitPointerLock();
  10700. };
  10701. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10702. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10703. }
  10704. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10705. Engine.audioEngine = new BABYLON.AudioEngine();
  10706. }
  10707. // Prepare buffer pointers
  10708. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10709. this._currentBufferPointers[i] = new BufferPointer();
  10710. }
  10711. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10712. // Load WebVR Devices
  10713. if (options.autoEnableWebVR) {
  10714. this.initWebVR();
  10715. }
  10716. // Detect if we are running on a faulty buggy OS.
  10717. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10718. // Detect if we are running on a faulty buggy desktop OS.
  10719. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10720. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10721. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10722. }
  10723. Object.defineProperty(Engine, "LastCreatedEngine", {
  10724. get: function () {
  10725. if (Engine.Instances.length === 0) {
  10726. return null;
  10727. }
  10728. return Engine.Instances[Engine.Instances.length - 1];
  10729. },
  10730. enumerable: true,
  10731. configurable: true
  10732. });
  10733. Object.defineProperty(Engine, "LastCreatedScene", {
  10734. get: function () {
  10735. var lastCreatedEngine = Engine.LastCreatedEngine;
  10736. if (!lastCreatedEngine) {
  10737. return null;
  10738. }
  10739. if (lastCreatedEngine.scenes.length === 0) {
  10740. return null;
  10741. }
  10742. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10743. },
  10744. enumerable: true,
  10745. configurable: true
  10746. });
  10747. /**
  10748. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10749. */
  10750. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10751. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10752. var engine = Engine.Instances[engineIndex];
  10753. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10754. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10755. }
  10756. }
  10757. };
  10758. Object.defineProperty(Engine, "NEVER", {
  10759. get: function () {
  10760. return Engine._NEVER;
  10761. },
  10762. enumerable: true,
  10763. configurable: true
  10764. });
  10765. Object.defineProperty(Engine, "ALWAYS", {
  10766. get: function () {
  10767. return Engine._ALWAYS;
  10768. },
  10769. enumerable: true,
  10770. configurable: true
  10771. });
  10772. Object.defineProperty(Engine, "LESS", {
  10773. get: function () {
  10774. return Engine._LESS;
  10775. },
  10776. enumerable: true,
  10777. configurable: true
  10778. });
  10779. Object.defineProperty(Engine, "EQUAL", {
  10780. get: function () {
  10781. return Engine._EQUAL;
  10782. },
  10783. enumerable: true,
  10784. configurable: true
  10785. });
  10786. Object.defineProperty(Engine, "LEQUAL", {
  10787. get: function () {
  10788. return Engine._LEQUAL;
  10789. },
  10790. enumerable: true,
  10791. configurable: true
  10792. });
  10793. Object.defineProperty(Engine, "GREATER", {
  10794. get: function () {
  10795. return Engine._GREATER;
  10796. },
  10797. enumerable: true,
  10798. configurable: true
  10799. });
  10800. Object.defineProperty(Engine, "GEQUAL", {
  10801. get: function () {
  10802. return Engine._GEQUAL;
  10803. },
  10804. enumerable: true,
  10805. configurable: true
  10806. });
  10807. Object.defineProperty(Engine, "NOTEQUAL", {
  10808. get: function () {
  10809. return Engine._NOTEQUAL;
  10810. },
  10811. enumerable: true,
  10812. configurable: true
  10813. });
  10814. Object.defineProperty(Engine, "KEEP", {
  10815. get: function () {
  10816. return Engine._KEEP;
  10817. },
  10818. enumerable: true,
  10819. configurable: true
  10820. });
  10821. Object.defineProperty(Engine, "REPLACE", {
  10822. get: function () {
  10823. return Engine._REPLACE;
  10824. },
  10825. enumerable: true,
  10826. configurable: true
  10827. });
  10828. Object.defineProperty(Engine, "INCR", {
  10829. get: function () {
  10830. return Engine._INCR;
  10831. },
  10832. enumerable: true,
  10833. configurable: true
  10834. });
  10835. Object.defineProperty(Engine, "DECR", {
  10836. get: function () {
  10837. return Engine._DECR;
  10838. },
  10839. enumerable: true,
  10840. configurable: true
  10841. });
  10842. Object.defineProperty(Engine, "INVERT", {
  10843. get: function () {
  10844. return Engine._INVERT;
  10845. },
  10846. enumerable: true,
  10847. configurable: true
  10848. });
  10849. Object.defineProperty(Engine, "INCR_WRAP", {
  10850. get: function () {
  10851. return Engine._INCR_WRAP;
  10852. },
  10853. enumerable: true,
  10854. configurable: true
  10855. });
  10856. Object.defineProperty(Engine, "DECR_WRAP", {
  10857. get: function () {
  10858. return Engine._DECR_WRAP;
  10859. },
  10860. enumerable: true,
  10861. configurable: true
  10862. });
  10863. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10864. get: function () {
  10865. return Engine._ALPHA_DISABLE;
  10866. },
  10867. enumerable: true,
  10868. configurable: true
  10869. });
  10870. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10871. get: function () {
  10872. return Engine._ALPHA_ONEONE;
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(Engine, "ALPHA_ADD", {
  10878. get: function () {
  10879. return Engine._ALPHA_ADD;
  10880. },
  10881. enumerable: true,
  10882. configurable: true
  10883. });
  10884. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10885. get: function () {
  10886. return Engine._ALPHA_COMBINE;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10892. get: function () {
  10893. return Engine._ALPHA_SUBTRACT;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10899. get: function () {
  10900. return Engine._ALPHA_MULTIPLY;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10906. get: function () {
  10907. return Engine._ALPHA_MAXIMIZED;
  10908. },
  10909. enumerable: true,
  10910. configurable: true
  10911. });
  10912. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10913. get: function () {
  10914. return Engine._ALPHA_PREMULTIPLIED;
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10920. get: function () {
  10921. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10922. },
  10923. enumerable: true,
  10924. configurable: true
  10925. });
  10926. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10927. get: function () {
  10928. return Engine._ALPHA_INTERPOLATE;
  10929. },
  10930. enumerable: true,
  10931. configurable: true
  10932. });
  10933. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10934. get: function () {
  10935. return Engine._ALPHA_SCREENMODE;
  10936. },
  10937. enumerable: true,
  10938. configurable: true
  10939. });
  10940. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10941. get: function () {
  10942. return Engine._DELAYLOADSTATE_NONE;
  10943. },
  10944. enumerable: true,
  10945. configurable: true
  10946. });
  10947. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10948. get: function () {
  10949. return Engine._DELAYLOADSTATE_LOADED;
  10950. },
  10951. enumerable: true,
  10952. configurable: true
  10953. });
  10954. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10955. get: function () {
  10956. return Engine._DELAYLOADSTATE_LOADING;
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10962. get: function () {
  10963. return Engine._DELAYLOADSTATE_NOTLOADED;
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10969. get: function () {
  10970. return Engine._TEXTUREFORMAT_ALPHA;
  10971. },
  10972. enumerable: true,
  10973. configurable: true
  10974. });
  10975. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10976. get: function () {
  10977. return Engine._TEXTUREFORMAT_LUMINANCE;
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10983. /**
  10984. * R32F
  10985. */
  10986. get: function () {
  10987. return Engine._TEXTUREFORMAT_R32F;
  10988. },
  10989. enumerable: true,
  10990. configurable: true
  10991. });
  10992. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10993. /**
  10994. * RG32F
  10995. */
  10996. get: function () {
  10997. return Engine._TEXTUREFORMAT_RG32F;
  10998. },
  10999. enumerable: true,
  11000. configurable: true
  11001. });
  11002. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11003. /**
  11004. * RGB32F
  11005. */
  11006. get: function () {
  11007. return Engine._TEXTUREFORMAT_RGB32F;
  11008. },
  11009. enumerable: true,
  11010. configurable: true
  11011. });
  11012. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11013. /**
  11014. * RGBA32F
  11015. */
  11016. get: function () {
  11017. return Engine._TEXTUREFORMAT_RGBA32F;
  11018. },
  11019. enumerable: true,
  11020. configurable: true
  11021. });
  11022. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11023. get: function () {
  11024. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11025. },
  11026. enumerable: true,
  11027. configurable: true
  11028. });
  11029. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11030. get: function () {
  11031. return Engine._TEXTUREFORMAT_RGB;
  11032. },
  11033. enumerable: true,
  11034. configurable: true
  11035. });
  11036. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11037. get: function () {
  11038. return Engine._TEXTUREFORMAT_RGBA;
  11039. },
  11040. enumerable: true,
  11041. configurable: true
  11042. });
  11043. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11044. get: function () {
  11045. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11046. },
  11047. enumerable: true,
  11048. configurable: true
  11049. });
  11050. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11051. get: function () {
  11052. return Engine._TEXTURETYPE_FLOAT;
  11053. },
  11054. enumerable: true,
  11055. configurable: true
  11056. });
  11057. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11058. get: function () {
  11059. return Engine._TEXTURETYPE_HALF_FLOAT;
  11060. },
  11061. enumerable: true,
  11062. configurable: true
  11063. });
  11064. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11065. get: function () {
  11066. return Engine._SCALEMODE_FLOOR;
  11067. },
  11068. enumerable: true,
  11069. configurable: true
  11070. });
  11071. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11072. get: function () {
  11073. return Engine._SCALEMODE_NEAREST;
  11074. },
  11075. enumerable: true,
  11076. configurable: true
  11077. });
  11078. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11079. get: function () {
  11080. return Engine._SCALEMODE_CEILING;
  11081. },
  11082. enumerable: true,
  11083. configurable: true
  11084. });
  11085. Object.defineProperty(Engine, "Version", {
  11086. get: function () {
  11087. return "3.2.0-alphaB";
  11088. },
  11089. enumerable: true,
  11090. configurable: true
  11091. });
  11092. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11093. get: function () {
  11094. return this._vrExclusivePointerMode;
  11095. },
  11096. enumerable: true,
  11097. configurable: true
  11098. });
  11099. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11100. get: function () {
  11101. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11102. },
  11103. enumerable: true,
  11104. configurable: true
  11105. });
  11106. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11107. get: function () {
  11108. return this._webGLVersion < 2 || this.forcePOTTextures;
  11109. },
  11110. enumerable: true,
  11111. configurable: true
  11112. });
  11113. Object.defineProperty(Engine.prototype, "badOS", {
  11114. get: function () {
  11115. return this._badOS;
  11116. },
  11117. enumerable: true,
  11118. configurable: true
  11119. });
  11120. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11121. get: function () {
  11122. return this._badDesktopOS;
  11123. },
  11124. enumerable: true,
  11125. configurable: true
  11126. });
  11127. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11128. get: function () {
  11129. return this._performanceMonitor;
  11130. },
  11131. enumerable: true,
  11132. configurable: true
  11133. });
  11134. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11135. get: function () {
  11136. return this._texturesSupported;
  11137. },
  11138. enumerable: true,
  11139. configurable: true
  11140. });
  11141. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11142. get: function () {
  11143. return this._textureFormatInUse;
  11144. },
  11145. enumerable: true,
  11146. configurable: true
  11147. });
  11148. Object.defineProperty(Engine.prototype, "currentViewport", {
  11149. get: function () {
  11150. return this._cachedViewport;
  11151. },
  11152. enumerable: true,
  11153. configurable: true
  11154. });
  11155. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11156. // Empty texture
  11157. get: function () {
  11158. if (!this._emptyTexture) {
  11159. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11160. }
  11161. return this._emptyTexture;
  11162. },
  11163. enumerable: true,
  11164. configurable: true
  11165. });
  11166. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11167. get: function () {
  11168. if (!this._emptyTexture3D) {
  11169. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11170. }
  11171. return this._emptyTexture3D;
  11172. },
  11173. enumerable: true,
  11174. configurable: true
  11175. });
  11176. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11177. get: function () {
  11178. if (!this._emptyCubeTexture) {
  11179. var faceData = new Uint8Array(4);
  11180. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11181. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11182. }
  11183. return this._emptyCubeTexture;
  11184. },
  11185. enumerable: true,
  11186. configurable: true
  11187. });
  11188. Engine.prototype._rebuildInternalTextures = function () {
  11189. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11190. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11191. var internalTexture = currentState_1[_i];
  11192. internalTexture._rebuild();
  11193. }
  11194. };
  11195. Engine.prototype._rebuildEffects = function () {
  11196. for (var key in this._compiledEffects) {
  11197. var effect = this._compiledEffects[key];
  11198. effect._prepareEffect();
  11199. }
  11200. BABYLON.Effect.ResetCache();
  11201. };
  11202. Engine.prototype._rebuildBuffers = function () {
  11203. // Index / Vertex
  11204. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11205. var scene = _a[_i];
  11206. scene.resetCachedMaterial();
  11207. scene._rebuildGeometries();
  11208. scene._rebuildTextures();
  11209. }
  11210. // Uniforms
  11211. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11212. var uniformBuffer = _c[_b];
  11213. uniformBuffer._rebuild();
  11214. }
  11215. };
  11216. Engine.prototype._initGLContext = function () {
  11217. // Caps
  11218. this._caps = new EngineCapabilities();
  11219. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11220. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11221. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11222. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11223. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11224. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11225. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11226. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11227. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11228. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11229. // Infos
  11230. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11231. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11232. if (rendererInfo != null) {
  11233. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11234. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11235. }
  11236. if (!this._glVendor) {
  11237. this._glVendor = "Unknown vendor";
  11238. }
  11239. if (!this._glRenderer) {
  11240. this._glRenderer = "Unknown renderer";
  11241. }
  11242. // Constants
  11243. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11244. if (this._gl.RGBA16F !== 0x881A) {
  11245. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11246. }
  11247. if (this._gl.RGBA32F !== 0x8814) {
  11248. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11249. }
  11250. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11251. this._gl.DEPTH24_STENCIL8 = 35056;
  11252. }
  11253. // Extensions
  11254. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11255. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11256. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11257. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11258. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11259. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11260. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11261. 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');
  11262. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11263. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11264. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11265. this._caps.highPrecisionShaderSupported = true;
  11266. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11267. if (this._caps.timerQuery) {
  11268. if (this._webGLVersion === 1) {
  11269. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11270. }
  11271. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11272. }
  11273. // Checks if some of the format renders first to allow the use of webgl inspector.
  11274. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11275. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11276. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11277. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11278. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11279. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11280. if (this._webGLVersion > 1) {
  11281. this._gl.HALF_FLOAT_OES = 0x140B;
  11282. }
  11283. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11284. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11285. // Draw buffers
  11286. if (this._webGLVersion > 1) {
  11287. this._caps.drawBuffersExtension = true;
  11288. }
  11289. else {
  11290. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11291. if (drawBuffersExtension !== null) {
  11292. this._caps.drawBuffersExtension = true;
  11293. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11294. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11295. for (var i = 0; i < 16; i++) {
  11296. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11297. }
  11298. }
  11299. else {
  11300. this._caps.drawBuffersExtension = false;
  11301. }
  11302. }
  11303. // Depth Texture
  11304. if (this._webGLVersion > 1) {
  11305. this._caps.depthTextureExtension = true;
  11306. }
  11307. else {
  11308. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11309. if (depthTextureExtension != null) {
  11310. this._caps.depthTextureExtension = true;
  11311. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11312. }
  11313. }
  11314. // Vertex array object
  11315. if (this._webGLVersion > 1) {
  11316. this._caps.vertexArrayObject = true;
  11317. }
  11318. else {
  11319. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11320. if (vertexArrayObjectExtension != null) {
  11321. this._caps.vertexArrayObject = true;
  11322. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11323. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11324. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11325. }
  11326. else {
  11327. this._caps.vertexArrayObject = false;
  11328. }
  11329. }
  11330. // Instances count
  11331. if (this._webGLVersion > 1) {
  11332. this._caps.instancedArrays = true;
  11333. }
  11334. else {
  11335. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11336. if (instanceExtension != null) {
  11337. this._caps.instancedArrays = true;
  11338. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11339. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11340. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11341. }
  11342. else {
  11343. this._caps.instancedArrays = false;
  11344. }
  11345. }
  11346. // Intelligently add supported compressed formats in order to check for.
  11347. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11348. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11349. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11350. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11351. if (this._caps.astc)
  11352. this.texturesSupported.push('-astc.ktx');
  11353. if (this._caps.s3tc)
  11354. this.texturesSupported.push('-dxt.ktx');
  11355. if (this._caps.pvrtc)
  11356. this.texturesSupported.push('-pvrtc.ktx');
  11357. if (this._caps.etc2)
  11358. this.texturesSupported.push('-etc2.ktx');
  11359. if (this._caps.etc1)
  11360. this.texturesSupported.push('-etc1.ktx');
  11361. if (this._gl.getShaderPrecisionFormat) {
  11362. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11363. if (highp) {
  11364. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11365. }
  11366. }
  11367. // Depth buffer
  11368. this.setDepthBuffer(true);
  11369. this.setDepthFunctionToLessOrEqual();
  11370. this.setDepthWrite(true);
  11371. // Texture maps
  11372. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11373. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11374. this._nextFreeTextureSlots.push(slot);
  11375. }
  11376. };
  11377. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11378. get: function () {
  11379. return this._webGLVersion;
  11380. },
  11381. enumerable: true,
  11382. configurable: true
  11383. });
  11384. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11385. /**
  11386. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11387. */
  11388. get: function () {
  11389. return this._isStencilEnable;
  11390. },
  11391. enumerable: true,
  11392. configurable: true
  11393. });
  11394. Engine.prototype._prepareWorkingCanvas = function () {
  11395. if (this._workingCanvas) {
  11396. return;
  11397. }
  11398. this._workingCanvas = document.createElement("canvas");
  11399. var context = this._workingCanvas.getContext("2d");
  11400. if (context) {
  11401. this._workingContext = context;
  11402. }
  11403. };
  11404. Engine.prototype.resetTextureCache = function () {
  11405. for (var key in this._boundTexturesCache) {
  11406. var boundTexture = this._boundTexturesCache[key];
  11407. if (boundTexture) {
  11408. this._removeDesignatedSlot(boundTexture);
  11409. }
  11410. this._boundTexturesCache[key] = null;
  11411. }
  11412. if (!this.disableTextureBindingOptimization) {
  11413. this._nextFreeTextureSlots = [];
  11414. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11415. this._nextFreeTextureSlots.push(slot);
  11416. }
  11417. }
  11418. this._currentTextureChannel = -1;
  11419. };
  11420. Engine.prototype.isDeterministicLockStep = function () {
  11421. return this._deterministicLockstep;
  11422. };
  11423. Engine.prototype.getLockstepMaxSteps = function () {
  11424. return this._lockstepMaxSteps;
  11425. };
  11426. Engine.prototype.getGlInfo = function () {
  11427. return {
  11428. vendor: this._glVendor,
  11429. renderer: this._glRenderer,
  11430. version: this._glVersion
  11431. };
  11432. };
  11433. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11434. if (useScreen === void 0) { useScreen = false; }
  11435. var viewport = camera.viewport;
  11436. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11437. };
  11438. Engine.prototype.getRenderWidth = function (useScreen) {
  11439. if (useScreen === void 0) { useScreen = false; }
  11440. if (!useScreen && this._currentRenderTarget) {
  11441. return this._currentRenderTarget.width;
  11442. }
  11443. return this._gl.drawingBufferWidth;
  11444. };
  11445. Engine.prototype.getRenderHeight = function (useScreen) {
  11446. if (useScreen === void 0) { useScreen = false; }
  11447. if (!useScreen && this._currentRenderTarget) {
  11448. return this._currentRenderTarget.height;
  11449. }
  11450. return this._gl.drawingBufferHeight;
  11451. };
  11452. Engine.prototype.getRenderingCanvas = function () {
  11453. return this._renderingCanvas;
  11454. };
  11455. Engine.prototype.getRenderingCanvasClientRect = function () {
  11456. if (!this._renderingCanvas) {
  11457. return null;
  11458. }
  11459. return this._renderingCanvas.getBoundingClientRect();
  11460. };
  11461. Engine.prototype.setHardwareScalingLevel = function (level) {
  11462. this._hardwareScalingLevel = level;
  11463. this.resize();
  11464. };
  11465. Engine.prototype.getHardwareScalingLevel = function () {
  11466. return this._hardwareScalingLevel;
  11467. };
  11468. Engine.prototype.getLoadedTexturesCache = function () {
  11469. return this._internalTexturesCache;
  11470. };
  11471. Engine.prototype.getCaps = function () {
  11472. return this._caps;
  11473. };
  11474. Object.defineProperty(Engine.prototype, "drawCalls", {
  11475. /** The number of draw calls submitted last frame */
  11476. get: function () {
  11477. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11478. return 0;
  11479. },
  11480. enumerable: true,
  11481. configurable: true
  11482. });
  11483. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11484. get: function () {
  11485. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11486. return null;
  11487. },
  11488. enumerable: true,
  11489. configurable: true
  11490. });
  11491. Engine.prototype.getDepthFunction = function () {
  11492. return this._depthCullingState.depthFunc;
  11493. };
  11494. Engine.prototype.setDepthFunction = function (depthFunc) {
  11495. this._depthCullingState.depthFunc = depthFunc;
  11496. };
  11497. Engine.prototype.setDepthFunctionToGreater = function () {
  11498. this._depthCullingState.depthFunc = this._gl.GREATER;
  11499. };
  11500. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11501. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11502. };
  11503. Engine.prototype.setDepthFunctionToLess = function () {
  11504. this._depthCullingState.depthFunc = this._gl.LESS;
  11505. };
  11506. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11507. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11508. };
  11509. Engine.prototype.getStencilBuffer = function () {
  11510. return this._stencilState.stencilTest;
  11511. };
  11512. Engine.prototype.setStencilBuffer = function (enable) {
  11513. this._stencilState.stencilTest = enable;
  11514. };
  11515. Engine.prototype.getStencilMask = function () {
  11516. return this._stencilState.stencilMask;
  11517. };
  11518. Engine.prototype.setStencilMask = function (mask) {
  11519. this._stencilState.stencilMask = mask;
  11520. };
  11521. Engine.prototype.getStencilFunction = function () {
  11522. return this._stencilState.stencilFunc;
  11523. };
  11524. Engine.prototype.getStencilFunctionReference = function () {
  11525. return this._stencilState.stencilFuncRef;
  11526. };
  11527. Engine.prototype.getStencilFunctionMask = function () {
  11528. return this._stencilState.stencilFuncMask;
  11529. };
  11530. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11531. this._stencilState.stencilFunc = stencilFunc;
  11532. };
  11533. Engine.prototype.setStencilFunctionReference = function (reference) {
  11534. this._stencilState.stencilFuncRef = reference;
  11535. };
  11536. Engine.prototype.setStencilFunctionMask = function (mask) {
  11537. this._stencilState.stencilFuncMask = mask;
  11538. };
  11539. Engine.prototype.getStencilOperationFail = function () {
  11540. return this._stencilState.stencilOpStencilFail;
  11541. };
  11542. Engine.prototype.getStencilOperationDepthFail = function () {
  11543. return this._stencilState.stencilOpDepthFail;
  11544. };
  11545. Engine.prototype.getStencilOperationPass = function () {
  11546. return this._stencilState.stencilOpStencilDepthPass;
  11547. };
  11548. Engine.prototype.setStencilOperationFail = function (operation) {
  11549. this._stencilState.stencilOpStencilFail = operation;
  11550. };
  11551. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11552. this._stencilState.stencilOpDepthFail = operation;
  11553. };
  11554. Engine.prototype.setStencilOperationPass = function (operation) {
  11555. this._stencilState.stencilOpStencilDepthPass = operation;
  11556. };
  11557. Engine.prototype.setDitheringState = function (value) {
  11558. if (value) {
  11559. this._gl.enable(this._gl.DITHER);
  11560. }
  11561. else {
  11562. this._gl.disable(this._gl.DITHER);
  11563. }
  11564. };
  11565. Engine.prototype.setRasterizerState = function (value) {
  11566. if (value) {
  11567. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11568. }
  11569. else {
  11570. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11571. }
  11572. };
  11573. /**
  11574. * stop executing a render loop function and remove it from the execution array
  11575. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11576. */
  11577. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11578. if (!renderFunction) {
  11579. this._activeRenderLoops = [];
  11580. return;
  11581. }
  11582. var index = this._activeRenderLoops.indexOf(renderFunction);
  11583. if (index >= 0) {
  11584. this._activeRenderLoops.splice(index, 1);
  11585. }
  11586. };
  11587. Engine.prototype._renderLoop = function () {
  11588. if (!this._contextWasLost) {
  11589. var shouldRender = true;
  11590. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11591. shouldRender = false;
  11592. }
  11593. if (shouldRender) {
  11594. // Start new frame
  11595. this.beginFrame();
  11596. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11597. var renderFunction = this._activeRenderLoops[index];
  11598. renderFunction();
  11599. }
  11600. // Present
  11601. this.endFrame();
  11602. }
  11603. }
  11604. if (this._activeRenderLoops.length > 0) {
  11605. // Register new frame
  11606. var requester = null;
  11607. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11608. requester = this._vrDisplay;
  11609. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11610. }
  11611. else {
  11612. this._renderingQueueLaunched = false;
  11613. }
  11614. };
  11615. /**
  11616. * Register and execute a render loop. The engine can have more than one render function.
  11617. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11618. * @example
  11619. * engine.runRenderLoop(function () {
  11620. * scene.render()
  11621. * })
  11622. */
  11623. Engine.prototype.runRenderLoop = function (renderFunction) {
  11624. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11625. return;
  11626. }
  11627. this._activeRenderLoops.push(renderFunction);
  11628. if (!this._renderingQueueLaunched) {
  11629. this._renderingQueueLaunched = true;
  11630. this._bindedRenderFunction = this._renderLoop.bind(this);
  11631. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11632. }
  11633. };
  11634. /**
  11635. * Toggle full screen mode.
  11636. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11637. * @param {any} options - an options object to be sent to the requestFullscreen function
  11638. */
  11639. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11640. if (this.isFullscreen) {
  11641. BABYLON.Tools.ExitFullscreen();
  11642. }
  11643. else {
  11644. this._pointerLockRequested = requestPointerLock;
  11645. if (this._renderingCanvas) {
  11646. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11647. }
  11648. }
  11649. };
  11650. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11651. if (stencil === void 0) { stencil = false; }
  11652. this.applyStates();
  11653. var mode = 0;
  11654. if (backBuffer && color) {
  11655. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11656. mode |= this._gl.COLOR_BUFFER_BIT;
  11657. }
  11658. if (depth) {
  11659. this._gl.clearDepth(1.0);
  11660. mode |= this._gl.DEPTH_BUFFER_BIT;
  11661. }
  11662. if (stencil) {
  11663. this._gl.clearStencil(0);
  11664. mode |= this._gl.STENCIL_BUFFER_BIT;
  11665. }
  11666. this._gl.clear(mode);
  11667. };
  11668. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11669. var gl = this._gl;
  11670. // Save state
  11671. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11672. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11673. // Change state
  11674. gl.enable(gl.SCISSOR_TEST);
  11675. gl.scissor(x, y, width, height);
  11676. // Clear
  11677. this.clear(clearColor, true, true, true);
  11678. // Restore state
  11679. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11680. if (curScissor === true) {
  11681. gl.enable(gl.SCISSOR_TEST);
  11682. }
  11683. else {
  11684. gl.disable(gl.SCISSOR_TEST);
  11685. }
  11686. };
  11687. /**
  11688. * Set the WebGL's viewport
  11689. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11690. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11691. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11692. */
  11693. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11694. var width = requiredWidth || this.getRenderWidth();
  11695. var height = requiredHeight || this.getRenderHeight();
  11696. var x = viewport.x || 0;
  11697. var y = viewport.y || 0;
  11698. this._cachedViewport = viewport;
  11699. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11700. };
  11701. /**
  11702. * Directly set the WebGL Viewport
  11703. * The x, y, width & height are directly passed to the WebGL call
  11704. * @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.
  11705. */
  11706. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11707. var currentViewport = this._cachedViewport;
  11708. this._cachedViewport = null;
  11709. this._gl.viewport(x, y, width, height);
  11710. return currentViewport;
  11711. };
  11712. Engine.prototype.beginFrame = function () {
  11713. this.onBeginFrameObservable.notifyObservers(this);
  11714. this._measureFps();
  11715. };
  11716. Engine.prototype.endFrame = function () {
  11717. //force a flush in case we are using a bad OS.
  11718. if (this._badOS) {
  11719. this.flushFramebuffer();
  11720. }
  11721. //submit frame to the vr device, if enabled
  11722. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11723. // TODO: We should only submit the frame if we read frameData successfully.
  11724. this._vrDisplay.submitFrame();
  11725. }
  11726. this.onEndFrameObservable.notifyObservers(this);
  11727. };
  11728. /**
  11729. * resize the view according to the canvas' size.
  11730. * @example
  11731. * window.addEventListener("resize", function () {
  11732. * engine.resize();
  11733. * });
  11734. */
  11735. Engine.prototype.resize = function () {
  11736. // We're not resizing the size of the canvas while in VR mode & presenting
  11737. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11738. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11739. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11740. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11741. }
  11742. };
  11743. /**
  11744. * force a specific size of the canvas
  11745. * @param {number} width - the new canvas' width
  11746. * @param {number} height - the new canvas' height
  11747. */
  11748. Engine.prototype.setSize = function (width, height) {
  11749. if (!this._renderingCanvas) {
  11750. return;
  11751. }
  11752. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11753. return;
  11754. }
  11755. this._renderingCanvas.width = width;
  11756. this._renderingCanvas.height = height;
  11757. for (var index = 0; index < this.scenes.length; index++) {
  11758. var scene = this.scenes[index];
  11759. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11760. var cam = scene.cameras[camIndex];
  11761. cam._currentRenderId = 0;
  11762. }
  11763. }
  11764. if (this.onResizeObservable.hasObservers) {
  11765. this.onResizeObservable.notifyObservers(this);
  11766. }
  11767. };
  11768. // WebVR functions
  11769. Engine.prototype.isVRDevicePresent = function () {
  11770. return !!this._vrDisplay;
  11771. };
  11772. Engine.prototype.getVRDevice = function () {
  11773. return this._vrDisplay;
  11774. };
  11775. /**
  11776. * Initializes a webVR display and starts listening to display change events.
  11777. * The onVRDisplayChangedObservable will be notified upon these changes.
  11778. * @returns The onVRDisplayChangedObservable.
  11779. */
  11780. Engine.prototype.initWebVR = function () {
  11781. this.initWebVRAsync();
  11782. return this.onVRDisplayChangedObservable;
  11783. };
  11784. /**
  11785. * Initializes a webVR display and starts listening to display change events.
  11786. * The onVRDisplayChangedObservable will be notified upon these changes.
  11787. * @returns A promise containing a VRDisplay and if vr is supported.
  11788. */
  11789. Engine.prototype.initWebVRAsync = function () {
  11790. var _this = this;
  11791. var notifyObservers = function () {
  11792. var eventArgs = {
  11793. vrDisplay: _this._vrDisplay,
  11794. vrSupported: _this._vrSupported
  11795. };
  11796. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11797. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11798. };
  11799. if (!this._onVrDisplayConnect) {
  11800. this._onVrDisplayConnect = function (event) {
  11801. _this._vrDisplay = event.display;
  11802. notifyObservers();
  11803. };
  11804. this._onVrDisplayDisconnect = function () {
  11805. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11806. _this._vrDisplay = undefined;
  11807. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11808. notifyObservers();
  11809. };
  11810. this._onVrDisplayPresentChange = function () {
  11811. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11812. };
  11813. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11814. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11815. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11816. }
  11817. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11818. this._webVRInitPromise.then(notifyObservers);
  11819. return this._webVRInitPromise;
  11820. };
  11821. Engine.prototype.enableVR = function () {
  11822. var _this = this;
  11823. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11824. var onResolved = function () {
  11825. _this.onVRRequestPresentComplete.notifyObservers(true);
  11826. _this._onVRFullScreenTriggered();
  11827. };
  11828. var onRejected = function () {
  11829. _this.onVRRequestPresentComplete.notifyObservers(false);
  11830. };
  11831. this.onVRRequestPresentStart.notifyObservers(this);
  11832. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11833. }
  11834. };
  11835. Engine.prototype.disableVR = function () {
  11836. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11837. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11838. }
  11839. };
  11840. Engine.prototype._getVRDisplaysAsync = function () {
  11841. var _this = this;
  11842. return new Promise(function (res, rej) {
  11843. if (navigator.getVRDisplays) {
  11844. navigator.getVRDisplays().then(function (devices) {
  11845. _this._vrSupported = true;
  11846. // note that devices may actually be an empty array. This is fine;
  11847. // we expect this._vrDisplay to be undefined in this case.
  11848. _this._vrDisplay = devices[0];
  11849. res({
  11850. vrDisplay: _this._vrDisplay,
  11851. vrSupported: _this._vrSupported
  11852. });
  11853. });
  11854. }
  11855. else {
  11856. _this._vrDisplay = undefined;
  11857. _this._vrSupported = false;
  11858. res({
  11859. vrDisplay: _this._vrDisplay,
  11860. vrSupported: _this._vrSupported
  11861. });
  11862. }
  11863. });
  11864. };
  11865. /**
  11866. * Binds the frame buffer to the specified texture.
  11867. * @param texture The texture to render to or null for the default canvas
  11868. * @param faceIndex The face of the texture to render to in case of cube texture
  11869. * @param requiredWidth The width of the target to render to
  11870. * @param requiredHeight The height of the target to render to
  11871. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11872. * @param depthStencilTexture The depth stencil texture to use to render
  11873. */
  11874. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11875. if (this._currentRenderTarget) {
  11876. this.unBindFramebuffer(this._currentRenderTarget);
  11877. }
  11878. this._currentRenderTarget = texture;
  11879. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11880. var gl = this._gl;
  11881. if (texture.isCube) {
  11882. if (faceIndex === undefined) {
  11883. faceIndex = 0;
  11884. }
  11885. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11886. if (depthStencilTexture) {
  11887. if (depthStencilTexture._generateStencilBuffer) {
  11888. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11889. }
  11890. else {
  11891. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11892. }
  11893. }
  11894. }
  11895. if (this._cachedViewport && !forceFullscreenViewport) {
  11896. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11897. }
  11898. else {
  11899. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11900. }
  11901. this.wipeCaches();
  11902. };
  11903. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11904. if (this._currentFramebuffer !== framebuffer) {
  11905. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11906. this._currentFramebuffer = framebuffer;
  11907. }
  11908. };
  11909. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11910. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11911. this._currentRenderTarget = null;
  11912. // If MSAA, we need to bitblt back to main texture
  11913. var gl = this._gl;
  11914. if (texture._MSAAFramebuffer) {
  11915. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11916. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11917. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11918. }
  11919. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11920. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11921. gl.generateMipmap(gl.TEXTURE_2D);
  11922. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11923. }
  11924. if (onBeforeUnbind) {
  11925. if (texture._MSAAFramebuffer) {
  11926. // Bind the correct framebuffer
  11927. this.bindUnboundFramebuffer(texture._framebuffer);
  11928. }
  11929. onBeforeUnbind();
  11930. }
  11931. this.bindUnboundFramebuffer(null);
  11932. };
  11933. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11934. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11935. this._currentRenderTarget = null;
  11936. // If MSAA, we need to bitblt back to main texture
  11937. var gl = this._gl;
  11938. if (textures[0]._MSAAFramebuffer) {
  11939. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11940. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11941. var attachments = textures[0]._attachments;
  11942. if (!attachments) {
  11943. attachments = new Array(textures.length);
  11944. textures[0]._attachments = attachments;
  11945. }
  11946. for (var i = 0; i < textures.length; i++) {
  11947. var texture = textures[i];
  11948. for (var j = 0; j < attachments.length; j++) {
  11949. attachments[j] = gl.NONE;
  11950. }
  11951. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11952. gl.readBuffer(attachments[i]);
  11953. gl.drawBuffers(attachments);
  11954. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11955. }
  11956. for (var i = 0; i < attachments.length; i++) {
  11957. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11958. }
  11959. gl.drawBuffers(attachments);
  11960. }
  11961. for (var i = 0; i < textures.length; i++) {
  11962. var texture = textures[i];
  11963. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11964. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11965. gl.generateMipmap(gl.TEXTURE_2D);
  11966. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11967. }
  11968. }
  11969. if (onBeforeUnbind) {
  11970. if (textures[0]._MSAAFramebuffer) {
  11971. // Bind the correct framebuffer
  11972. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11973. }
  11974. onBeforeUnbind();
  11975. }
  11976. this.bindUnboundFramebuffer(null);
  11977. };
  11978. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11979. if (texture.generateMipMaps) {
  11980. var gl = this._gl;
  11981. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11982. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11983. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11984. }
  11985. };
  11986. Engine.prototype.flushFramebuffer = function () {
  11987. this._gl.flush();
  11988. };
  11989. Engine.prototype.restoreDefaultFramebuffer = function () {
  11990. if (this._currentRenderTarget) {
  11991. this.unBindFramebuffer(this._currentRenderTarget);
  11992. }
  11993. else {
  11994. this.bindUnboundFramebuffer(null);
  11995. }
  11996. if (this._cachedViewport) {
  11997. this.setViewport(this._cachedViewport);
  11998. }
  11999. this.wipeCaches();
  12000. };
  12001. // UBOs
  12002. Engine.prototype.createUniformBuffer = function (elements) {
  12003. var ubo = this._gl.createBuffer();
  12004. if (!ubo) {
  12005. throw new Error("Unable to create uniform buffer");
  12006. }
  12007. this.bindUniformBuffer(ubo);
  12008. if (elements instanceof Float32Array) {
  12009. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12010. }
  12011. else {
  12012. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12013. }
  12014. this.bindUniformBuffer(null);
  12015. ubo.references = 1;
  12016. return ubo;
  12017. };
  12018. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12019. var ubo = this._gl.createBuffer();
  12020. if (!ubo) {
  12021. throw new Error("Unable to create dynamic uniform buffer");
  12022. }
  12023. this.bindUniformBuffer(ubo);
  12024. if (elements instanceof Float32Array) {
  12025. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12026. }
  12027. else {
  12028. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12029. }
  12030. this.bindUniformBuffer(null);
  12031. ubo.references = 1;
  12032. return ubo;
  12033. };
  12034. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12035. this.bindUniformBuffer(uniformBuffer);
  12036. if (offset === undefined) {
  12037. offset = 0;
  12038. }
  12039. if (count === undefined) {
  12040. if (elements instanceof Float32Array) {
  12041. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12042. }
  12043. else {
  12044. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12045. }
  12046. }
  12047. else {
  12048. if (elements instanceof Float32Array) {
  12049. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12050. }
  12051. else {
  12052. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12053. }
  12054. }
  12055. this.bindUniformBuffer(null);
  12056. };
  12057. // VBOs
  12058. Engine.prototype._resetVertexBufferBinding = function () {
  12059. this.bindArrayBuffer(null);
  12060. this._cachedVertexBuffers = null;
  12061. };
  12062. Engine.prototype.createVertexBuffer = function (vertices) {
  12063. var vbo = this._gl.createBuffer();
  12064. if (!vbo) {
  12065. throw new Error("Unable to create vertex buffer");
  12066. }
  12067. this.bindArrayBuffer(vbo);
  12068. if (vertices instanceof Float32Array) {
  12069. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12070. }
  12071. else {
  12072. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12073. }
  12074. this._resetVertexBufferBinding();
  12075. vbo.references = 1;
  12076. return vbo;
  12077. };
  12078. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12079. var vbo = this._gl.createBuffer();
  12080. if (!vbo) {
  12081. throw new Error("Unable to create dynamic vertex buffer");
  12082. }
  12083. this.bindArrayBuffer(vbo);
  12084. if (vertices instanceof Float32Array) {
  12085. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12086. }
  12087. else {
  12088. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12089. }
  12090. this._resetVertexBufferBinding();
  12091. vbo.references = 1;
  12092. return vbo;
  12093. };
  12094. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12095. if (offset === void 0) { offset = 0; }
  12096. // Force cache update
  12097. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12098. this.bindIndexBuffer(indexBuffer);
  12099. var arrayBuffer;
  12100. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12101. arrayBuffer = indices;
  12102. }
  12103. else {
  12104. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12105. }
  12106. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12107. this._resetIndexBufferBinding();
  12108. };
  12109. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12110. this.bindArrayBuffer(vertexBuffer);
  12111. if (offset === undefined) {
  12112. offset = 0;
  12113. }
  12114. if (count === undefined) {
  12115. if (vertices instanceof Float32Array) {
  12116. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12117. }
  12118. else {
  12119. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12120. }
  12121. }
  12122. else {
  12123. if (vertices instanceof Float32Array) {
  12124. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12125. }
  12126. else {
  12127. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12128. }
  12129. }
  12130. this._resetVertexBufferBinding();
  12131. };
  12132. Engine.prototype._resetIndexBufferBinding = function () {
  12133. this.bindIndexBuffer(null);
  12134. this._cachedIndexBuffer = null;
  12135. };
  12136. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12137. var vbo = this._gl.createBuffer();
  12138. if (!vbo) {
  12139. throw new Error("Unable to create index buffer");
  12140. }
  12141. this.bindIndexBuffer(vbo);
  12142. // Check for 32 bits indices
  12143. var arrayBuffer;
  12144. var need32Bits = false;
  12145. if (indices instanceof Uint16Array) {
  12146. arrayBuffer = indices;
  12147. }
  12148. else {
  12149. //check 32 bit support
  12150. if (this._caps.uintIndices) {
  12151. if (indices instanceof Uint32Array) {
  12152. arrayBuffer = indices;
  12153. need32Bits = true;
  12154. }
  12155. else {
  12156. //number[] or Int32Array, check if 32 bit is necessary
  12157. for (var index = 0; index < indices.length; index++) {
  12158. if (indices[index] > 65535) {
  12159. need32Bits = true;
  12160. break;
  12161. }
  12162. }
  12163. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12164. }
  12165. }
  12166. else {
  12167. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12168. arrayBuffer = new Uint16Array(indices);
  12169. }
  12170. }
  12171. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12172. this._resetIndexBufferBinding();
  12173. vbo.references = 1;
  12174. vbo.is32Bits = need32Bits;
  12175. return vbo;
  12176. };
  12177. Engine.prototype.bindArrayBuffer = function (buffer) {
  12178. if (!this._vaoRecordInProgress) {
  12179. this._unbindVertexArrayObject();
  12180. }
  12181. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12182. };
  12183. Engine.prototype.bindUniformBuffer = function (buffer) {
  12184. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12185. };
  12186. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12187. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12188. };
  12189. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12190. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12191. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12192. };
  12193. ;
  12194. Engine.prototype.bindIndexBuffer = function (buffer) {
  12195. if (!this._vaoRecordInProgress) {
  12196. this._unbindVertexArrayObject();
  12197. }
  12198. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12199. };
  12200. Engine.prototype.bindBuffer = function (buffer, target) {
  12201. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12202. this._gl.bindBuffer(target, buffer);
  12203. this._currentBoundBuffer[target] = buffer;
  12204. }
  12205. };
  12206. Engine.prototype.updateArrayBuffer = function (data) {
  12207. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12208. };
  12209. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12210. var pointer = this._currentBufferPointers[indx];
  12211. var changed = false;
  12212. if (!pointer.active) {
  12213. changed = true;
  12214. pointer.active = true;
  12215. pointer.index = indx;
  12216. pointer.size = size;
  12217. pointer.type = type;
  12218. pointer.normalized = normalized;
  12219. pointer.stride = stride;
  12220. pointer.offset = offset;
  12221. pointer.buffer = buffer;
  12222. }
  12223. else {
  12224. if (pointer.buffer !== buffer) {
  12225. pointer.buffer = buffer;
  12226. changed = true;
  12227. }
  12228. if (pointer.size !== size) {
  12229. pointer.size = size;
  12230. changed = true;
  12231. }
  12232. if (pointer.type !== type) {
  12233. pointer.type = type;
  12234. changed = true;
  12235. }
  12236. if (pointer.normalized !== normalized) {
  12237. pointer.normalized = normalized;
  12238. changed = true;
  12239. }
  12240. if (pointer.stride !== stride) {
  12241. pointer.stride = stride;
  12242. changed = true;
  12243. }
  12244. if (pointer.offset !== offset) {
  12245. pointer.offset = offset;
  12246. changed = true;
  12247. }
  12248. }
  12249. if (changed || this._vaoRecordInProgress) {
  12250. this.bindArrayBuffer(buffer);
  12251. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12252. }
  12253. };
  12254. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12255. if (indexBuffer == null) {
  12256. return;
  12257. }
  12258. if (this._cachedIndexBuffer !== indexBuffer) {
  12259. this._cachedIndexBuffer = indexBuffer;
  12260. this.bindIndexBuffer(indexBuffer);
  12261. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12262. }
  12263. };
  12264. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12265. var attributes = effect.getAttributesNames();
  12266. if (!this._vaoRecordInProgress) {
  12267. this._unbindVertexArrayObject();
  12268. }
  12269. this.unbindAllAttributes();
  12270. for (var index = 0; index < attributes.length; index++) {
  12271. var order = effect.getAttributeLocation(index);
  12272. if (order >= 0) {
  12273. var vertexBuffer = vertexBuffers[attributes[index]];
  12274. if (!vertexBuffer) {
  12275. continue;
  12276. }
  12277. this._gl.enableVertexAttribArray(order);
  12278. if (!this._vaoRecordInProgress) {
  12279. this._vertexAttribArraysEnabled[order] = true;
  12280. }
  12281. var buffer = vertexBuffer.getBuffer();
  12282. if (buffer) {
  12283. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12284. if (vertexBuffer.getIsInstanced()) {
  12285. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12286. if (!this._vaoRecordInProgress) {
  12287. this._currentInstanceLocations.push(order);
  12288. this._currentInstanceBuffers.push(buffer);
  12289. }
  12290. }
  12291. }
  12292. }
  12293. }
  12294. };
  12295. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12296. var vao = this._gl.createVertexArray();
  12297. this._vaoRecordInProgress = true;
  12298. this._gl.bindVertexArray(vao);
  12299. this._mustWipeVertexAttributes = true;
  12300. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12301. this.bindIndexBuffer(indexBuffer);
  12302. this._vaoRecordInProgress = false;
  12303. this._gl.bindVertexArray(null);
  12304. return vao;
  12305. };
  12306. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12307. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12308. this._cachedVertexArrayObject = vertexArrayObject;
  12309. this._gl.bindVertexArray(vertexArrayObject);
  12310. this._cachedVertexBuffers = null;
  12311. this._cachedIndexBuffer = null;
  12312. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12313. this._mustWipeVertexAttributes = true;
  12314. }
  12315. };
  12316. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12317. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12318. this._cachedVertexBuffers = vertexBuffer;
  12319. this._cachedEffectForVertexBuffers = effect;
  12320. var attributesCount = effect.getAttributesCount();
  12321. this._unbindVertexArrayObject();
  12322. this.unbindAllAttributes();
  12323. var offset = 0;
  12324. for (var index = 0; index < attributesCount; index++) {
  12325. if (index < vertexDeclaration.length) {
  12326. var order = effect.getAttributeLocation(index);
  12327. if (order >= 0) {
  12328. this._gl.enableVertexAttribArray(order);
  12329. this._vertexAttribArraysEnabled[order] = true;
  12330. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12331. }
  12332. offset += vertexDeclaration[index] * 4;
  12333. }
  12334. }
  12335. }
  12336. this._bindIndexBufferWithCache(indexBuffer);
  12337. };
  12338. Engine.prototype._unbindVertexArrayObject = function () {
  12339. if (!this._cachedVertexArrayObject) {
  12340. return;
  12341. }
  12342. this._cachedVertexArrayObject = null;
  12343. this._gl.bindVertexArray(null);
  12344. };
  12345. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12346. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12347. this._cachedVertexBuffers = vertexBuffers;
  12348. this._cachedEffectForVertexBuffers = effect;
  12349. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12350. }
  12351. this._bindIndexBufferWithCache(indexBuffer);
  12352. };
  12353. Engine.prototype.unbindInstanceAttributes = function () {
  12354. var boundBuffer;
  12355. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12356. var instancesBuffer = this._currentInstanceBuffers[i];
  12357. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12358. boundBuffer = instancesBuffer;
  12359. this.bindArrayBuffer(instancesBuffer);
  12360. }
  12361. var offsetLocation = this._currentInstanceLocations[i];
  12362. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12363. }
  12364. this._currentInstanceBuffers.length = 0;
  12365. this._currentInstanceLocations.length = 0;
  12366. };
  12367. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12368. this._gl.deleteVertexArray(vao);
  12369. };
  12370. Engine.prototype._releaseBuffer = function (buffer) {
  12371. buffer.references--;
  12372. if (buffer.references === 0) {
  12373. this._gl.deleteBuffer(buffer);
  12374. return true;
  12375. }
  12376. return false;
  12377. };
  12378. Engine.prototype.createInstancesBuffer = function (capacity) {
  12379. var buffer = this._gl.createBuffer();
  12380. if (!buffer) {
  12381. throw new Error("Unable to create instance buffer");
  12382. }
  12383. buffer.capacity = capacity;
  12384. this.bindArrayBuffer(buffer);
  12385. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12386. return buffer;
  12387. };
  12388. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12389. this._gl.deleteBuffer(buffer);
  12390. };
  12391. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12392. this.bindArrayBuffer(instancesBuffer);
  12393. if (data) {
  12394. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12395. }
  12396. if (offsetLocations[0].index !== undefined) {
  12397. var stride = 0;
  12398. for (var i = 0; i < offsetLocations.length; i++) {
  12399. var ai = offsetLocations[i];
  12400. stride += ai.attributeSize * 4;
  12401. }
  12402. for (var i = 0; i < offsetLocations.length; i++) {
  12403. var ai = offsetLocations[i];
  12404. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12405. this._gl.enableVertexAttribArray(ai.index);
  12406. this._vertexAttribArraysEnabled[ai.index] = true;
  12407. }
  12408. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12409. this._gl.vertexAttribDivisor(ai.index, 1);
  12410. this._currentInstanceLocations.push(ai.index);
  12411. this._currentInstanceBuffers.push(instancesBuffer);
  12412. }
  12413. }
  12414. else {
  12415. for (var index = 0; index < 4; index++) {
  12416. var offsetLocation = offsetLocations[index];
  12417. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12418. this._gl.enableVertexAttribArray(offsetLocation);
  12419. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12420. }
  12421. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12422. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12423. this._currentInstanceLocations.push(offsetLocation);
  12424. this._currentInstanceBuffers.push(instancesBuffer);
  12425. }
  12426. }
  12427. };
  12428. Engine.prototype.applyStates = function () {
  12429. this._depthCullingState.apply(this._gl);
  12430. this._stencilState.apply(this._gl);
  12431. this._alphaState.apply(this._gl);
  12432. };
  12433. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12434. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12435. };
  12436. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12437. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12438. };
  12439. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12440. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12441. };
  12442. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12443. // Apply states
  12444. this.applyStates();
  12445. this._drawCalls.addCount(1, false);
  12446. // Render
  12447. var drawMode = this.DrawMode(fillMode);
  12448. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12449. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12450. if (instancesCount) {
  12451. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12452. }
  12453. else {
  12454. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12455. }
  12456. };
  12457. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12458. // Apply states
  12459. this.applyStates();
  12460. this._drawCalls.addCount(1, false);
  12461. var drawMode = this.DrawMode(fillMode);
  12462. if (instancesCount) {
  12463. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12464. }
  12465. else {
  12466. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12467. }
  12468. };
  12469. Engine.prototype.DrawMode = function (fillMode) {
  12470. switch (fillMode) {
  12471. // Triangle views
  12472. case BABYLON.Material.TriangleFillMode:
  12473. return this._gl.TRIANGLES;
  12474. case BABYLON.Material.PointFillMode:
  12475. return this._gl.POINTS;
  12476. case BABYLON.Material.WireFrameFillMode:
  12477. return this._gl.LINES;
  12478. // Draw modes
  12479. case BABYLON.Material.PointListDrawMode:
  12480. return this._gl.POINTS;
  12481. case BABYLON.Material.LineListDrawMode:
  12482. return this._gl.LINES;
  12483. case BABYLON.Material.LineLoopDrawMode:
  12484. return this._gl.LINE_LOOP;
  12485. case BABYLON.Material.LineStripDrawMode:
  12486. return this._gl.LINE_STRIP;
  12487. case BABYLON.Material.TriangleStripDrawMode:
  12488. return this._gl.TRIANGLE_STRIP;
  12489. case BABYLON.Material.TriangleFanDrawMode:
  12490. return this._gl.TRIANGLE_FAN;
  12491. default:
  12492. return this._gl.TRIANGLES;
  12493. }
  12494. };
  12495. // Shaders
  12496. Engine.prototype._releaseEffect = function (effect) {
  12497. if (this._compiledEffects[effect._key]) {
  12498. delete this._compiledEffects[effect._key];
  12499. this._deleteProgram(effect.getProgram());
  12500. }
  12501. };
  12502. Engine.prototype._deleteProgram = function (program) {
  12503. if (program) {
  12504. program.__SPECTOR_rebuildProgram = null;
  12505. if (program.transformFeedback) {
  12506. this.deleteTransformFeedback(program.transformFeedback);
  12507. program.transformFeedback = null;
  12508. }
  12509. this._gl.deleteProgram(program);
  12510. }
  12511. };
  12512. /**
  12513. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12514. * @param samplers An array of string used to represent textures
  12515. */
  12516. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12517. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12518. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12519. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12520. if (this._compiledEffects[name]) {
  12521. var compiledEffect = this._compiledEffects[name];
  12522. if (onCompiled && compiledEffect.isReady()) {
  12523. onCompiled(compiledEffect);
  12524. }
  12525. return compiledEffect;
  12526. }
  12527. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12528. effect._key = name;
  12529. this._compiledEffects[name] = effect;
  12530. return effect;
  12531. };
  12532. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12533. if (uniformsNames === void 0) { uniformsNames = []; }
  12534. if (samplers === void 0) { samplers = []; }
  12535. if (defines === void 0) { defines = ""; }
  12536. return this.createEffect({
  12537. vertex: "particles",
  12538. fragmentElement: fragmentName
  12539. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12540. };
  12541. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12542. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12543. context = context || this._gl;
  12544. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12545. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12546. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12547. };
  12548. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12549. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12550. context = context || this._gl;
  12551. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12552. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12553. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12554. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12555. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12556. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12557. return program;
  12558. };
  12559. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12560. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12561. var shaderProgram = context.createProgram();
  12562. if (!shaderProgram) {
  12563. throw new Error("Unable to create program");
  12564. }
  12565. context.attachShader(shaderProgram, vertexShader);
  12566. context.attachShader(shaderProgram, fragmentShader);
  12567. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12568. var transformFeedback = this.createTransformFeedback();
  12569. this.bindTransformFeedback(transformFeedback);
  12570. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12571. shaderProgram.transformFeedback = transformFeedback;
  12572. }
  12573. context.linkProgram(shaderProgram);
  12574. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12575. this.bindTransformFeedback(null);
  12576. }
  12577. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12578. if (!linked) {
  12579. context.validateProgram(shaderProgram);
  12580. var error = context.getProgramInfoLog(shaderProgram);
  12581. if (error) {
  12582. throw new Error(error);
  12583. }
  12584. }
  12585. context.deleteShader(vertexShader);
  12586. context.deleteShader(fragmentShader);
  12587. return shaderProgram;
  12588. };
  12589. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12590. var results = new Array();
  12591. for (var index = 0; index < uniformsNames.length; index++) {
  12592. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12593. }
  12594. return results;
  12595. };
  12596. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12597. var results = [];
  12598. for (var index = 0; index < attributesNames.length; index++) {
  12599. try {
  12600. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12601. }
  12602. catch (e) {
  12603. results.push(-1);
  12604. }
  12605. }
  12606. return results;
  12607. };
  12608. Engine.prototype.enableEffect = function (effect) {
  12609. if (!effect) {
  12610. return;
  12611. }
  12612. // Use program
  12613. this.bindSamplers(effect);
  12614. this._currentEffect = effect;
  12615. if (effect.onBind) {
  12616. effect.onBind(effect);
  12617. }
  12618. effect.onBindObservable.notifyObservers(effect);
  12619. };
  12620. Engine.prototype.setIntArray = function (uniform, array) {
  12621. if (!uniform)
  12622. return;
  12623. this._gl.uniform1iv(uniform, array);
  12624. };
  12625. Engine.prototype.setIntArray2 = function (uniform, array) {
  12626. if (!uniform || array.length % 2 !== 0)
  12627. return;
  12628. this._gl.uniform2iv(uniform, array);
  12629. };
  12630. Engine.prototype.setIntArray3 = function (uniform, array) {
  12631. if (!uniform || array.length % 3 !== 0)
  12632. return;
  12633. this._gl.uniform3iv(uniform, array);
  12634. };
  12635. Engine.prototype.setIntArray4 = function (uniform, array) {
  12636. if (!uniform || array.length % 4 !== 0)
  12637. return;
  12638. this._gl.uniform4iv(uniform, array);
  12639. };
  12640. Engine.prototype.setFloatArray = function (uniform, array) {
  12641. if (!uniform)
  12642. return;
  12643. this._gl.uniform1fv(uniform, array);
  12644. };
  12645. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12646. if (!uniform || array.length % 2 !== 0)
  12647. return;
  12648. this._gl.uniform2fv(uniform, array);
  12649. };
  12650. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12651. if (!uniform || array.length % 3 !== 0)
  12652. return;
  12653. this._gl.uniform3fv(uniform, array);
  12654. };
  12655. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12656. if (!uniform || array.length % 4 !== 0)
  12657. return;
  12658. this._gl.uniform4fv(uniform, array);
  12659. };
  12660. Engine.prototype.setArray = function (uniform, array) {
  12661. if (!uniform)
  12662. return;
  12663. this._gl.uniform1fv(uniform, array);
  12664. };
  12665. Engine.prototype.setArray2 = function (uniform, array) {
  12666. if (!uniform || array.length % 2 !== 0)
  12667. return;
  12668. this._gl.uniform2fv(uniform, array);
  12669. };
  12670. Engine.prototype.setArray3 = function (uniform, array) {
  12671. if (!uniform || array.length % 3 !== 0)
  12672. return;
  12673. this._gl.uniform3fv(uniform, array);
  12674. };
  12675. Engine.prototype.setArray4 = function (uniform, array) {
  12676. if (!uniform || array.length % 4 !== 0)
  12677. return;
  12678. this._gl.uniform4fv(uniform, array);
  12679. };
  12680. Engine.prototype.setMatrices = function (uniform, matrices) {
  12681. if (!uniform)
  12682. return;
  12683. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12684. };
  12685. Engine.prototype.setMatrix = function (uniform, matrix) {
  12686. if (!uniform)
  12687. return;
  12688. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12689. };
  12690. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12691. if (!uniform)
  12692. return;
  12693. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12694. };
  12695. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12696. if (!uniform)
  12697. return;
  12698. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12699. };
  12700. Engine.prototype.setInt = function (uniform, value) {
  12701. if (!uniform)
  12702. return;
  12703. this._gl.uniform1i(uniform, value);
  12704. };
  12705. Engine.prototype.setFloat = function (uniform, value) {
  12706. if (!uniform)
  12707. return;
  12708. this._gl.uniform1f(uniform, value);
  12709. };
  12710. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12711. if (!uniform)
  12712. return;
  12713. this._gl.uniform2f(uniform, x, y);
  12714. };
  12715. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12716. if (!uniform)
  12717. return;
  12718. this._gl.uniform3f(uniform, x, y, z);
  12719. };
  12720. Engine.prototype.setBool = function (uniform, bool) {
  12721. if (!uniform)
  12722. return;
  12723. this._gl.uniform1i(uniform, bool);
  12724. };
  12725. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12726. if (!uniform)
  12727. return;
  12728. this._gl.uniform4f(uniform, x, y, z, w);
  12729. };
  12730. Engine.prototype.setColor3 = function (uniform, color3) {
  12731. if (!uniform)
  12732. return;
  12733. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12734. };
  12735. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12736. if (!uniform)
  12737. return;
  12738. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12739. };
  12740. /**
  12741. * Sets a Color4 on a uniform variable
  12742. * @param uniform defines the uniform location
  12743. * @param color4 defines the value to be set
  12744. */
  12745. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12746. if (!uniform)
  12747. return;
  12748. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12749. };
  12750. // States
  12751. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12752. if (zOffset === void 0) { zOffset = 0; }
  12753. if (reverseSide === void 0) { reverseSide = false; }
  12754. // Culling
  12755. if (this._depthCullingState.cull !== culling || force) {
  12756. this._depthCullingState.cull = culling;
  12757. }
  12758. // Cull face
  12759. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12760. if (this._depthCullingState.cullFace !== cullFace || force) {
  12761. this._depthCullingState.cullFace = cullFace;
  12762. }
  12763. // Z offset
  12764. this.setZOffset(zOffset);
  12765. // Front face
  12766. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12767. if (this._depthCullingState.frontFace !== frontFace || force) {
  12768. this._depthCullingState.frontFace = frontFace;
  12769. }
  12770. };
  12771. Engine.prototype.setZOffset = function (value) {
  12772. this._depthCullingState.zOffset = value;
  12773. };
  12774. Engine.prototype.getZOffset = function () {
  12775. return this._depthCullingState.zOffset;
  12776. };
  12777. Engine.prototype.setDepthBuffer = function (enable) {
  12778. this._depthCullingState.depthTest = enable;
  12779. };
  12780. Engine.prototype.getDepthWrite = function () {
  12781. return this._depthCullingState.depthMask;
  12782. };
  12783. Engine.prototype.setDepthWrite = function (enable) {
  12784. this._depthCullingState.depthMask = enable;
  12785. };
  12786. Engine.prototype.setColorWrite = function (enable) {
  12787. this._gl.colorMask(enable, enable, enable, enable);
  12788. this._colorWrite = enable;
  12789. };
  12790. Engine.prototype.getColorWrite = function () {
  12791. return this._colorWrite;
  12792. };
  12793. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12794. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12795. };
  12796. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12797. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12798. if (this._alphaMode === mode) {
  12799. return;
  12800. }
  12801. switch (mode) {
  12802. case Engine.ALPHA_DISABLE:
  12803. this._alphaState.alphaBlend = false;
  12804. break;
  12805. case Engine.ALPHA_PREMULTIPLIED:
  12806. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12807. this._alphaState.alphaBlend = true;
  12808. break;
  12809. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12810. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12811. this._alphaState.alphaBlend = true;
  12812. break;
  12813. case Engine.ALPHA_COMBINE:
  12814. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12815. this._alphaState.alphaBlend = true;
  12816. break;
  12817. case Engine.ALPHA_ONEONE:
  12818. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12819. this._alphaState.alphaBlend = true;
  12820. break;
  12821. case Engine.ALPHA_ADD:
  12822. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12823. this._alphaState.alphaBlend = true;
  12824. break;
  12825. case Engine.ALPHA_SUBTRACT:
  12826. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12827. this._alphaState.alphaBlend = true;
  12828. break;
  12829. case Engine.ALPHA_MULTIPLY:
  12830. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12831. this._alphaState.alphaBlend = true;
  12832. break;
  12833. case Engine.ALPHA_MAXIMIZED:
  12834. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12835. this._alphaState.alphaBlend = true;
  12836. break;
  12837. case Engine.ALPHA_INTERPOLATE:
  12838. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12839. this._alphaState.alphaBlend = true;
  12840. break;
  12841. case Engine.ALPHA_SCREENMODE:
  12842. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12843. this._alphaState.alphaBlend = true;
  12844. break;
  12845. }
  12846. if (!noDepthWriteChange) {
  12847. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12848. }
  12849. this._alphaMode = mode;
  12850. };
  12851. Engine.prototype.getAlphaMode = function () {
  12852. return this._alphaMode;
  12853. };
  12854. // Textures
  12855. Engine.prototype.wipeCaches = function (bruteForce) {
  12856. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12857. return;
  12858. }
  12859. this._currentEffect = null;
  12860. // 6/8/2017: deltakosh: Should not be required anymore.
  12861. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12862. if (bruteForce) {
  12863. this.resetTextureCache();
  12864. this._currentProgram = null;
  12865. this._stencilState.reset();
  12866. this._depthCullingState.reset();
  12867. this.setDepthFunctionToLessOrEqual();
  12868. this._alphaState.reset();
  12869. }
  12870. this._resetVertexBufferBinding();
  12871. this._cachedIndexBuffer = null;
  12872. this._cachedEffectForVertexBuffers = null;
  12873. this._unbindVertexArrayObject();
  12874. this.bindIndexBuffer(null);
  12875. };
  12876. /**
  12877. * Set the compressed texture format to use, based on the formats you have, and the formats
  12878. * supported by the hardware / browser.
  12879. *
  12880. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12881. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12882. * to API arguments needed to compressed textures. This puts the burden on the container
  12883. * generator to house the arcane code for determining these for current & future formats.
  12884. *
  12885. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12886. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12887. *
  12888. * Note: The result of this call is not taken into account when a texture is base64.
  12889. *
  12890. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12891. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12892. *
  12893. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12894. * @returns The extension selected.
  12895. */
  12896. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12897. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12898. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12899. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12900. return this._textureFormatInUse = this._texturesSupported[i];
  12901. }
  12902. }
  12903. }
  12904. // actively set format to nothing, to allow this to be called more than once
  12905. // and possibly fail the 2nd time
  12906. this._textureFormatInUse = null;
  12907. return null;
  12908. };
  12909. Engine.prototype._createTexture = function () {
  12910. var texture = this._gl.createTexture();
  12911. if (!texture) {
  12912. throw new Error("Unable to create texture");
  12913. }
  12914. return texture;
  12915. };
  12916. /**
  12917. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12918. * @param {string} urlArg- This contains one of the following:
  12919. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12920. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12921. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12922. *
  12923. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12924. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12925. * @param {Scene} scene- Needed for loading to the correct scene.
  12926. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12927. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12928. * @param {callback} onError- Optional callback to be called upon failure.
  12929. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12930. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12931. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12932. *
  12933. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12934. */
  12935. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12936. var _this = this;
  12937. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12938. if (onLoad === void 0) { onLoad = null; }
  12939. if (onError === void 0) { onError = null; }
  12940. if (buffer === void 0) { buffer = null; }
  12941. if (fallBack === void 0) { fallBack = null; }
  12942. if (format === void 0) { format = null; }
  12943. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12944. var fromData = url.substr(0, 5) === "data:";
  12945. var fromBlob = url.substr(0, 5) === "blob:";
  12946. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12947. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12948. // establish the file extension, if possible
  12949. var lastDot = url.lastIndexOf('.');
  12950. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12951. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12952. var isTGA = (extension.indexOf(".tga") === 0);
  12953. // determine if a ktx file should be substituted
  12954. var isKTX = false;
  12955. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12956. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12957. isKTX = true;
  12958. }
  12959. if (scene) {
  12960. scene._addPendingData(texture);
  12961. }
  12962. texture.url = url;
  12963. texture.generateMipMaps = !noMipmap;
  12964. texture.samplingMode = samplingMode;
  12965. texture.invertY = invertY;
  12966. if (!this._doNotHandleContextLost) {
  12967. // Keep a link to the buffer only if we plan to handle context lost
  12968. texture._buffer = buffer;
  12969. }
  12970. var onLoadObserver = null;
  12971. if (onLoad && !fallBack) {
  12972. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12973. }
  12974. if (!fallBack)
  12975. this._internalTexturesCache.push(texture);
  12976. var onerror = function (message, exception) {
  12977. if (scene) {
  12978. scene._removePendingData(texture);
  12979. }
  12980. if (onLoadObserver) {
  12981. texture.onLoadedObservable.remove(onLoadObserver);
  12982. }
  12983. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12984. if (isKTX) {
  12985. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12986. }
  12987. else if (BABYLON.Tools.UseFallbackTexture) {
  12988. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12989. }
  12990. if (onError) {
  12991. onError(message || "Unknown error", exception);
  12992. }
  12993. };
  12994. var callback = null;
  12995. // processing for non-image formats
  12996. if (isKTX || isTGA || isDDS) {
  12997. if (isKTX) {
  12998. callback = function (data) {
  12999. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13000. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13001. ktx.uploadLevels(_this._gl, !noMipmap);
  13002. return false;
  13003. }, samplingMode);
  13004. };
  13005. }
  13006. else if (isTGA) {
  13007. callback = function (arrayBuffer) {
  13008. var data = new Uint8Array(arrayBuffer);
  13009. var header = BABYLON.TGATools.GetTGAHeader(data);
  13010. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13011. BABYLON.TGATools.UploadContent(_this._gl, data);
  13012. return false;
  13013. }, samplingMode);
  13014. };
  13015. }
  13016. else if (isDDS) {
  13017. callback = function (data) {
  13018. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13019. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13020. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13021. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13022. return false;
  13023. }, samplingMode);
  13024. };
  13025. }
  13026. if (!buffer) {
  13027. this._loadFile(url, function (data) {
  13028. if (callback) {
  13029. callback(data);
  13030. }
  13031. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13032. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13033. });
  13034. }
  13035. else {
  13036. if (callback) {
  13037. callback(buffer);
  13038. }
  13039. }
  13040. // image format processing
  13041. }
  13042. else {
  13043. var onload = function (img) {
  13044. if (fromBlob && !_this._doNotHandleContextLost) {
  13045. // We need to store the image if we need to rebuild the texture
  13046. // in case of a webgl context lost
  13047. texture._buffer = img;
  13048. }
  13049. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13050. var gl = _this._gl;
  13051. var isPot = (img.width === potWidth && img.height === potHeight);
  13052. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13053. if (isPot) {
  13054. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13055. return false;
  13056. }
  13057. // Using shaders to rescale because canvas.drawImage is lossy
  13058. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13059. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13060. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13061. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13062. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13064. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13065. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13066. _this._releaseTexture(source);
  13067. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13068. continuationCallback();
  13069. });
  13070. return true;
  13071. }, samplingMode);
  13072. };
  13073. if (!fromData || isBase64)
  13074. if (buffer instanceof HTMLImageElement) {
  13075. onload(buffer);
  13076. }
  13077. else {
  13078. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13079. }
  13080. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13081. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13082. else
  13083. onload(buffer);
  13084. }
  13085. return texture;
  13086. };
  13087. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13088. var _this = this;
  13089. var rtt = this.createRenderTargetTexture({
  13090. width: destination.width,
  13091. height: destination.height,
  13092. }, {
  13093. generateMipMaps: false,
  13094. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13095. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13096. generateDepthBuffer: false,
  13097. generateStencilBuffer: false
  13098. });
  13099. if (!this._rescalePostProcess) {
  13100. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13101. }
  13102. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13103. _this._rescalePostProcess.onApply = function (effect) {
  13104. effect._bindTexture("textureSampler", source);
  13105. };
  13106. var hostingScene = scene;
  13107. if (!hostingScene) {
  13108. hostingScene = _this.scenes[_this.scenes.length - 1];
  13109. }
  13110. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13111. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13112. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13113. _this.unBindFramebuffer(rtt);
  13114. _this._releaseTexture(rtt);
  13115. if (onComplete) {
  13116. onComplete();
  13117. }
  13118. });
  13119. };
  13120. Engine.prototype._getInternalFormat = function (format) {
  13121. var internalFormat = this._gl.RGBA;
  13122. switch (format) {
  13123. case Engine.TEXTUREFORMAT_ALPHA:
  13124. internalFormat = this._gl.ALPHA;
  13125. break;
  13126. case Engine.TEXTUREFORMAT_LUMINANCE:
  13127. internalFormat = this._gl.LUMINANCE;
  13128. break;
  13129. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13130. internalFormat = this._gl.LUMINANCE_ALPHA;
  13131. break;
  13132. case Engine.TEXTUREFORMAT_RGB:
  13133. case Engine.TEXTUREFORMAT_RGB32F:
  13134. internalFormat = this._gl.RGB;
  13135. break;
  13136. case Engine.TEXTUREFORMAT_RGBA:
  13137. case Engine.TEXTUREFORMAT_RGBA32F:
  13138. internalFormat = this._gl.RGBA;
  13139. break;
  13140. case Engine.TEXTUREFORMAT_R32F:
  13141. internalFormat = this._gl.RED;
  13142. break;
  13143. case Engine.TEXTUREFORMAT_RG32F:
  13144. internalFormat = this._gl.RG;
  13145. break;
  13146. }
  13147. return internalFormat;
  13148. };
  13149. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13150. if (compression === void 0) { compression = null; }
  13151. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13152. if (!texture) {
  13153. return;
  13154. }
  13155. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13156. var internalFormat = this._getInternalFormat(format);
  13157. var textureType = this._getWebGLTextureType(type);
  13158. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13159. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13160. if (!this._doNotHandleContextLost) {
  13161. texture._bufferView = data;
  13162. texture.format = format;
  13163. texture.type = type;
  13164. texture.invertY = invertY;
  13165. texture._compression = compression;
  13166. }
  13167. if (texture.width % 4 !== 0) {
  13168. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13169. }
  13170. if (compression && data) {
  13171. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13172. }
  13173. else {
  13174. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13175. }
  13176. if (texture.generateMipMaps) {
  13177. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13178. }
  13179. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13180. // this.resetTextureCache();
  13181. texture.isReady = true;
  13182. };
  13183. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13184. if (compression === void 0) { compression = null; }
  13185. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13186. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13187. texture.baseWidth = width;
  13188. texture.baseHeight = height;
  13189. texture.width = width;
  13190. texture.height = height;
  13191. texture.format = format;
  13192. texture.generateMipMaps = generateMipMaps;
  13193. texture.samplingMode = samplingMode;
  13194. texture.invertY = invertY;
  13195. texture._compression = compression;
  13196. texture.type = type;
  13197. if (!this._doNotHandleContextLost) {
  13198. texture._bufferView = data;
  13199. }
  13200. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13201. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13202. // Filters
  13203. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13204. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13205. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13206. if (generateMipMaps) {
  13207. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13208. }
  13209. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13210. this._internalTexturesCache.push(texture);
  13211. return texture;
  13212. };
  13213. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13214. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13215. texture.baseWidth = width;
  13216. texture.baseHeight = height;
  13217. if (generateMipMaps) {
  13218. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13219. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13220. }
  13221. // this.resetTextureCache();
  13222. texture.width = width;
  13223. texture.height = height;
  13224. texture.isReady = false;
  13225. texture.generateMipMaps = generateMipMaps;
  13226. texture.samplingMode = samplingMode;
  13227. this.updateTextureSamplingMode(samplingMode, texture);
  13228. this._internalTexturesCache.push(texture);
  13229. return texture;
  13230. };
  13231. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13232. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13233. if (texture.isCube) {
  13234. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13235. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13236. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13237. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13238. }
  13239. else if (texture.is3D) {
  13240. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13241. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13242. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13243. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13244. }
  13245. else {
  13246. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13247. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13248. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13249. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13250. }
  13251. texture.samplingMode = samplingMode;
  13252. };
  13253. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13254. if (premulAlpha === void 0) { premulAlpha = false; }
  13255. if (!texture) {
  13256. return;
  13257. }
  13258. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13259. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13260. if (premulAlpha) {
  13261. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13262. }
  13263. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13264. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13265. if (texture.generateMipMaps) {
  13266. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13267. }
  13268. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13269. if (premulAlpha) {
  13270. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13271. }
  13272. texture.isReady = true;
  13273. };
  13274. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13275. if (!texture || texture._isDisabled) {
  13276. return;
  13277. }
  13278. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13279. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13280. try {
  13281. // Testing video texture support
  13282. if (this._videoTextureSupported === undefined) {
  13283. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13284. if (this._gl.getError() !== 0) {
  13285. this._videoTextureSupported = false;
  13286. }
  13287. else {
  13288. this._videoTextureSupported = true;
  13289. }
  13290. }
  13291. // Copy video through the current working canvas if video texture is not supported
  13292. if (!this._videoTextureSupported) {
  13293. if (!texture._workingCanvas) {
  13294. texture._workingCanvas = document.createElement("canvas");
  13295. var context = texture._workingCanvas.getContext("2d");
  13296. if (!context) {
  13297. throw new Error("Unable to get 2d context");
  13298. }
  13299. texture._workingContext = context;
  13300. texture._workingCanvas.width = texture.width;
  13301. texture._workingCanvas.height = texture.height;
  13302. }
  13303. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13304. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13305. }
  13306. else {
  13307. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13308. }
  13309. if (texture.generateMipMaps) {
  13310. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13311. }
  13312. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13313. // this.resetTextureCache();
  13314. texture.isReady = true;
  13315. }
  13316. catch (ex) {
  13317. // Something unexpected
  13318. // Let's disable the texture
  13319. texture._isDisabled = true;
  13320. }
  13321. };
  13322. /**
  13323. * Updates a depth texture Comparison Mode and Function.
  13324. * If the comparison Function is equal to 0, the mode will be set to none.
  13325. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13326. * @param texture The texture to set the comparison function for
  13327. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13328. */
  13329. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13330. if (this.webGLVersion === 1) {
  13331. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13332. return;
  13333. }
  13334. var gl = this._gl;
  13335. if (texture.isCube) {
  13336. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13337. if (comparisonFunction === 0) {
  13338. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13339. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13340. }
  13341. else {
  13342. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13343. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13344. }
  13345. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13346. }
  13347. else {
  13348. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13349. if (comparisonFunction === 0) {
  13350. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13351. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13352. }
  13353. else {
  13354. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13355. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13356. }
  13357. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13358. }
  13359. texture._comparisonFunction = comparisonFunction;
  13360. };
  13361. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13362. var width = size.width || size;
  13363. var height = size.height || size;
  13364. internalTexture.baseWidth = width;
  13365. internalTexture.baseHeight = height;
  13366. internalTexture.width = width;
  13367. internalTexture.height = height;
  13368. internalTexture.isReady = true;
  13369. internalTexture.samples = 1;
  13370. internalTexture.generateMipMaps = false;
  13371. internalTexture._generateDepthBuffer = true;
  13372. internalTexture._generateStencilBuffer = generateStencil;
  13373. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13374. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13375. internalTexture._comparisonFunction = comparisonFunction;
  13376. var gl = this._gl;
  13377. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13378. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13379. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13380. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13381. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13382. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13383. if (comparisonFunction === 0) {
  13384. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13385. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13386. }
  13387. else {
  13388. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13389. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13390. }
  13391. };
  13392. /**
  13393. * Creates a depth stencil texture.
  13394. * This is only available in WebGL 2 or with the depth texture extension available.
  13395. * @param size The size of face edge in the texture.
  13396. * @param options The options defining the texture.
  13397. * @returns The texture
  13398. */
  13399. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13400. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13401. if (!this._caps.depthTextureExtension) {
  13402. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13403. return internalTexture;
  13404. }
  13405. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13406. var gl = this._gl;
  13407. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13408. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13409. if (this.webGLVersion > 1) {
  13410. if (internalOptions.generateStencil) {
  13411. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13412. }
  13413. else {
  13414. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13415. }
  13416. }
  13417. else {
  13418. if (internalOptions.generateStencil) {
  13419. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13420. }
  13421. else {
  13422. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13423. }
  13424. }
  13425. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13426. return internalTexture;
  13427. };
  13428. /**
  13429. * Creates a depth stencil cube texture.
  13430. * This is only available in WebGL 2.
  13431. * @param size The size of face edge in the cube texture.
  13432. * @param options The options defining the cube texture.
  13433. * @returns The cube texture
  13434. */
  13435. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13436. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13437. internalTexture.isCube = true;
  13438. if (this.webGLVersion === 1) {
  13439. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13440. return internalTexture;
  13441. }
  13442. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13443. var gl = this._gl;
  13444. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13445. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13446. // Create the depth/stencil buffer
  13447. for (var face = 0; face < 6; face++) {
  13448. if (internalOptions.generateStencil) {
  13449. 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);
  13450. }
  13451. else {
  13452. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13453. }
  13454. }
  13455. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13456. return internalTexture;
  13457. };
  13458. /**
  13459. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13460. * @param renderTarget The render target to set the frame buffer for
  13461. */
  13462. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13463. // Create the framebuffer
  13464. var internalTexture = renderTarget.getInternalTexture();
  13465. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13466. return;
  13467. }
  13468. var gl = this._gl;
  13469. var depthStencilTexture = renderTarget.depthStencilTexture;
  13470. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13471. if (depthStencilTexture.isCube) {
  13472. if (depthStencilTexture._generateStencilBuffer) {
  13473. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13474. }
  13475. else {
  13476. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13477. }
  13478. }
  13479. else {
  13480. if (depthStencilTexture._generateStencilBuffer) {
  13481. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13482. }
  13483. else {
  13484. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13485. }
  13486. }
  13487. this.bindUnboundFramebuffer(null);
  13488. };
  13489. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13490. var fullOptions = new RenderTargetCreationOptions();
  13491. if (options !== undefined && typeof options === "object") {
  13492. fullOptions.generateMipMaps = options.generateMipMaps;
  13493. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13494. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13495. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13496. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13497. }
  13498. else {
  13499. fullOptions.generateMipMaps = options;
  13500. fullOptions.generateDepthBuffer = true;
  13501. fullOptions.generateStencilBuffer = false;
  13502. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13503. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13504. }
  13505. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13506. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13507. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13508. }
  13509. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13510. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13511. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13512. }
  13513. var gl = this._gl;
  13514. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13515. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13516. var width = size.width || size;
  13517. var height = size.height || size;
  13518. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13519. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13520. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13521. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13522. }
  13523. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13524. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13525. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13526. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13527. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13528. // Create the framebuffer
  13529. var framebuffer = gl.createFramebuffer();
  13530. this.bindUnboundFramebuffer(framebuffer);
  13531. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13532. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13533. if (fullOptions.generateMipMaps) {
  13534. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13535. }
  13536. // Unbind
  13537. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13538. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13539. this.bindUnboundFramebuffer(null);
  13540. texture._framebuffer = framebuffer;
  13541. texture.baseWidth = width;
  13542. texture.baseHeight = height;
  13543. texture.width = width;
  13544. texture.height = height;
  13545. texture.isReady = true;
  13546. texture.samples = 1;
  13547. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13548. texture.samplingMode = fullOptions.samplingMode;
  13549. texture.type = fullOptions.type;
  13550. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13551. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13552. // this.resetTextureCache();
  13553. this._internalTexturesCache.push(texture);
  13554. return texture;
  13555. };
  13556. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13557. var generateMipMaps = false;
  13558. var generateDepthBuffer = true;
  13559. var generateStencilBuffer = false;
  13560. var generateDepthTexture = false;
  13561. var textureCount = 1;
  13562. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13563. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13564. var types = [], samplingModes = [];
  13565. if (options !== undefined) {
  13566. generateMipMaps = options.generateMipMaps;
  13567. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13568. generateStencilBuffer = options.generateStencilBuffer;
  13569. generateDepthTexture = options.generateDepthTexture;
  13570. textureCount = options.textureCount || 1;
  13571. if (options.types) {
  13572. types = options.types;
  13573. }
  13574. if (options.samplingModes) {
  13575. samplingModes = options.samplingModes;
  13576. }
  13577. }
  13578. var gl = this._gl;
  13579. // Create the framebuffer
  13580. var framebuffer = gl.createFramebuffer();
  13581. this.bindUnboundFramebuffer(framebuffer);
  13582. var width = size.width || size;
  13583. var height = size.height || size;
  13584. var textures = [];
  13585. var attachments = [];
  13586. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13587. for (var i = 0; i < textureCount; i++) {
  13588. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13589. var type = types[i] || defaultType;
  13590. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13591. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13592. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13593. }
  13594. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13595. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13596. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13597. }
  13598. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13599. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13600. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13601. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13602. }
  13603. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13604. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13605. textures.push(texture);
  13606. attachments.push(attachment);
  13607. gl.activeTexture(gl["TEXTURE" + i]);
  13608. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13609. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13610. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13611. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13612. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13613. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13614. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13615. if (generateMipMaps) {
  13616. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13617. }
  13618. // Unbind
  13619. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13620. texture._framebuffer = framebuffer;
  13621. texture._depthStencilBuffer = depthStencilBuffer;
  13622. texture.baseWidth = width;
  13623. texture.baseHeight = height;
  13624. texture.width = width;
  13625. texture.height = height;
  13626. texture.isReady = true;
  13627. texture.samples = 1;
  13628. texture.generateMipMaps = generateMipMaps;
  13629. texture.samplingMode = samplingMode;
  13630. texture.type = type;
  13631. texture._generateDepthBuffer = generateDepthBuffer;
  13632. texture._generateStencilBuffer = generateStencilBuffer;
  13633. texture._attachments = attachments;
  13634. this._internalTexturesCache.push(texture);
  13635. }
  13636. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13637. // Depth texture
  13638. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13639. gl.activeTexture(gl.TEXTURE0);
  13640. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13641. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13642. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13643. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13644. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13645. 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);
  13646. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13647. depthTexture._framebuffer = framebuffer;
  13648. depthTexture.baseWidth = width;
  13649. depthTexture.baseHeight = height;
  13650. depthTexture.width = width;
  13651. depthTexture.height = height;
  13652. depthTexture.isReady = true;
  13653. depthTexture.samples = 1;
  13654. depthTexture.generateMipMaps = generateMipMaps;
  13655. depthTexture.samplingMode = gl.NEAREST;
  13656. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13657. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13658. textures.push(depthTexture);
  13659. this._internalTexturesCache.push(depthTexture);
  13660. }
  13661. gl.drawBuffers(attachments);
  13662. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13663. this.bindUnboundFramebuffer(null);
  13664. this.resetTextureCache();
  13665. return textures;
  13666. };
  13667. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13668. if (samples === void 0) { samples = 1; }
  13669. var depthStencilBuffer = null;
  13670. var gl = this._gl;
  13671. // Create the depth/stencil buffer
  13672. if (generateStencilBuffer) {
  13673. depthStencilBuffer = gl.createRenderbuffer();
  13674. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13675. if (samples > 1) {
  13676. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13677. }
  13678. else {
  13679. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13680. }
  13681. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13682. }
  13683. else if (generateDepthBuffer) {
  13684. depthStencilBuffer = gl.createRenderbuffer();
  13685. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13686. if (samples > 1) {
  13687. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13688. }
  13689. else {
  13690. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13691. }
  13692. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13693. }
  13694. return depthStencilBuffer;
  13695. };
  13696. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13697. if (this.webGLVersion < 2 || !texture) {
  13698. return 1;
  13699. }
  13700. if (texture.samples === samples) {
  13701. return samples;
  13702. }
  13703. var gl = this._gl;
  13704. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13705. // Dispose previous render buffers
  13706. if (texture._depthStencilBuffer) {
  13707. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13708. texture._depthStencilBuffer = null;
  13709. }
  13710. if (texture._MSAAFramebuffer) {
  13711. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13712. texture._MSAAFramebuffer = null;
  13713. }
  13714. if (texture._MSAARenderBuffer) {
  13715. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13716. texture._MSAARenderBuffer = null;
  13717. }
  13718. if (samples > 1) {
  13719. var framebuffer = gl.createFramebuffer();
  13720. if (!framebuffer) {
  13721. throw new Error("Unable to create multi sampled framebuffer");
  13722. }
  13723. texture._MSAAFramebuffer = framebuffer;
  13724. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13725. var colorRenderbuffer = gl.createRenderbuffer();
  13726. if (!colorRenderbuffer) {
  13727. throw new Error("Unable to create multi sampled framebuffer");
  13728. }
  13729. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13730. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13731. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13732. texture._MSAARenderBuffer = colorRenderbuffer;
  13733. }
  13734. else {
  13735. this.bindUnboundFramebuffer(texture._framebuffer);
  13736. }
  13737. texture.samples = samples;
  13738. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13739. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13740. this.bindUnboundFramebuffer(null);
  13741. return samples;
  13742. };
  13743. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13744. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13745. return 1;
  13746. }
  13747. if (textures[0].samples === samples) {
  13748. return samples;
  13749. }
  13750. var gl = this._gl;
  13751. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13752. // Dispose previous render buffers
  13753. if (textures[0]._depthStencilBuffer) {
  13754. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13755. textures[0]._depthStencilBuffer = null;
  13756. }
  13757. if (textures[0]._MSAAFramebuffer) {
  13758. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13759. textures[0]._MSAAFramebuffer = null;
  13760. }
  13761. for (var i = 0; i < textures.length; i++) {
  13762. if (textures[i]._MSAARenderBuffer) {
  13763. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13764. textures[i]._MSAARenderBuffer = null;
  13765. }
  13766. }
  13767. if (samples > 1) {
  13768. var framebuffer = gl.createFramebuffer();
  13769. if (!framebuffer) {
  13770. throw new Error("Unable to create multi sampled framebuffer");
  13771. }
  13772. this.bindUnboundFramebuffer(framebuffer);
  13773. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13774. var attachments = [];
  13775. for (var i = 0; i < textures.length; i++) {
  13776. var texture = textures[i];
  13777. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13778. var colorRenderbuffer = gl.createRenderbuffer();
  13779. if (!colorRenderbuffer) {
  13780. throw new Error("Unable to create multi sampled framebuffer");
  13781. }
  13782. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13783. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13784. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13785. texture._MSAAFramebuffer = framebuffer;
  13786. texture._MSAARenderBuffer = colorRenderbuffer;
  13787. texture.samples = samples;
  13788. texture._depthStencilBuffer = depthStencilBuffer;
  13789. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13790. attachments.push(attachment);
  13791. }
  13792. gl.drawBuffers(attachments);
  13793. }
  13794. else {
  13795. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13796. }
  13797. this.bindUnboundFramebuffer(null);
  13798. return samples;
  13799. };
  13800. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13801. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13802. };
  13803. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13804. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13805. };
  13806. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13807. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13808. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13809. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13810. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13811. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13812. }
  13813. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13814. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13815. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13816. }
  13817. var gl = this._gl;
  13818. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13819. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13820. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13821. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13822. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13823. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13824. }
  13825. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13827. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13828. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13829. for (var face = 0; face < 6; face++) {
  13830. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13831. }
  13832. // Create the framebuffer
  13833. var framebuffer = gl.createFramebuffer();
  13834. this.bindUnboundFramebuffer(framebuffer);
  13835. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13836. // MipMaps
  13837. if (fullOptions.generateMipMaps) {
  13838. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13839. }
  13840. // Unbind
  13841. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13842. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13843. this.bindUnboundFramebuffer(null);
  13844. texture._framebuffer = framebuffer;
  13845. texture.width = size;
  13846. texture.height = size;
  13847. texture.isReady = true;
  13848. texture.isCube = true;
  13849. texture.samples = 1;
  13850. texture.generateMipMaps = fullOptions.generateMipMaps;
  13851. texture.samplingMode = fullOptions.samplingMode;
  13852. texture.type = fullOptions.type;
  13853. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13854. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13855. this._internalTexturesCache.push(texture);
  13856. return texture;
  13857. };
  13858. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13859. var _this = this;
  13860. if (onLoad === void 0) { onLoad = null; }
  13861. if (onError === void 0) { onError = null; }
  13862. if (forcedExtension === void 0) { forcedExtension = null; }
  13863. var callback = function (loadData) {
  13864. if (!loadData) {
  13865. if (onLoad) {
  13866. onLoad(null);
  13867. }
  13868. return;
  13869. }
  13870. var texture = loadData.texture;
  13871. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13872. texture._lodGenerationScale = scale;
  13873. texture._lodGenerationOffset = offset;
  13874. if (_this._caps.textureLOD) {
  13875. // Do not add extra process if texture lod is supported.
  13876. if (onLoad) {
  13877. onLoad(texture);
  13878. }
  13879. return;
  13880. }
  13881. var mipSlices = 3;
  13882. var gl = _this._gl;
  13883. var width = loadData.width;
  13884. if (!width) {
  13885. return;
  13886. }
  13887. var textures = [];
  13888. for (var i = 0; i < mipSlices; i++) {
  13889. //compute LOD from even spacing in smoothness (matching shader calculation)
  13890. var smoothness = i / (mipSlices - 1);
  13891. var roughness = 1 - smoothness;
  13892. var minLODIndex = offset; // roughness = 0
  13893. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13894. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13895. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13896. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13897. glTextureFromLod.isCube = true;
  13898. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13899. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13900. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13901. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13903. if (loadData.isDDS) {
  13904. var info = loadData.info;
  13905. var data = loadData.data;
  13906. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13907. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13908. }
  13909. else {
  13910. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13911. }
  13912. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13913. // Wrap in a base texture for easy binding.
  13914. var lodTexture = new BABYLON.BaseTexture(scene);
  13915. lodTexture.isCube = true;
  13916. lodTexture._texture = glTextureFromLod;
  13917. glTextureFromLod.isReady = true;
  13918. textures.push(lodTexture);
  13919. }
  13920. texture._lodTextureHigh = textures[2];
  13921. texture._lodTextureMid = textures[1];
  13922. texture._lodTextureLow = textures[0];
  13923. if (onLoad) {
  13924. onLoad(texture);
  13925. }
  13926. };
  13927. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13928. };
  13929. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13930. var _this = this;
  13931. if (onLoad === void 0) { onLoad = null; }
  13932. if (onError === void 0) { onError = null; }
  13933. if (forcedExtension === void 0) { forcedExtension = null; }
  13934. var gl = this._gl;
  13935. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13936. texture.isCube = true;
  13937. texture.url = rootUrl;
  13938. texture.generateMipMaps = !noMipmap;
  13939. if (!this._doNotHandleContextLost) {
  13940. texture._extension = forcedExtension;
  13941. texture._files = files;
  13942. }
  13943. var isKTX = false;
  13944. var isDDS = false;
  13945. var lastDot = rootUrl.lastIndexOf('.');
  13946. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13947. if (this._textureFormatInUse) {
  13948. extension = this._textureFormatInUse;
  13949. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13950. isKTX = true;
  13951. }
  13952. else {
  13953. isDDS = (extension === ".dds");
  13954. }
  13955. var onerror = function (request, exception) {
  13956. if (onError && request) {
  13957. onError(request.status + " " + request.statusText, exception);
  13958. }
  13959. };
  13960. if (isKTX) {
  13961. this._loadFile(rootUrl, function (data) {
  13962. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13963. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13964. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13965. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13966. ktx.uploadLevels(_this._gl, !noMipmap);
  13967. _this.setCubeMapTextureParams(gl, loadMipmap);
  13968. texture.width = ktx.pixelWidth;
  13969. texture.height = ktx.pixelHeight;
  13970. texture.isReady = true;
  13971. }, undefined, undefined, true, onerror);
  13972. }
  13973. else if (isDDS) {
  13974. if (files && files.length === 6) {
  13975. this._cascadeLoadFiles(scene, function (imgs) {
  13976. var info;
  13977. var loadMipmap = false;
  13978. var width = 0;
  13979. for (var index = 0; index < imgs.length; index++) {
  13980. var data = imgs[index];
  13981. info = BABYLON.DDSTools.GetDDSInfo(data);
  13982. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13983. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13984. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13985. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13986. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13987. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13988. }
  13989. texture.width = info.width;
  13990. texture.height = info.height;
  13991. texture.type = info.textureType;
  13992. width = info.width;
  13993. }
  13994. _this.setCubeMapTextureParams(gl, loadMipmap);
  13995. texture.isReady = true;
  13996. if (onLoad) {
  13997. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13998. }
  13999. }, files, onError);
  14000. }
  14001. else {
  14002. this._loadFile(rootUrl, function (data) {
  14003. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14004. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14005. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14006. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14007. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14008. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14009. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14010. }
  14011. _this.setCubeMapTextureParams(gl, loadMipmap);
  14012. texture.width = info.width;
  14013. texture.height = info.height;
  14014. texture.isReady = true;
  14015. texture.type = info.textureType;
  14016. if (onLoad) {
  14017. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14018. }
  14019. }, undefined, undefined, true, onerror);
  14020. }
  14021. }
  14022. else {
  14023. if (!files) {
  14024. throw new Error("Cannot load cubemap because files were not defined");
  14025. }
  14026. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14027. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14028. var height = width;
  14029. _this._prepareWorkingCanvas();
  14030. if (!_this._workingCanvas || !_this._workingContext) {
  14031. return;
  14032. }
  14033. _this._workingCanvas.width = width;
  14034. _this._workingCanvas.height = height;
  14035. var faces = [
  14036. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14037. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14038. ];
  14039. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14040. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14041. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14042. for (var index = 0; index < faces.length; index++) {
  14043. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14044. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14045. }
  14046. if (!noMipmap) {
  14047. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14048. }
  14049. _this.setCubeMapTextureParams(gl, !noMipmap);
  14050. texture.width = width;
  14051. texture.height = height;
  14052. texture.isReady = true;
  14053. if (format) {
  14054. texture.format = format;
  14055. }
  14056. texture.onLoadedObservable.notifyObservers(texture);
  14057. texture.onLoadedObservable.clear();
  14058. if (onLoad) {
  14059. onLoad();
  14060. }
  14061. }, files, onError);
  14062. }
  14063. this._internalTexturesCache.push(texture);
  14064. return texture;
  14065. };
  14066. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14069. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14070. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14071. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14072. // this.resetTextureCache();
  14073. };
  14074. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14075. if (compression === void 0) { compression = null; }
  14076. if (level === void 0) { level = 0; }
  14077. texture._bufferViewArray = data;
  14078. texture.format = format;
  14079. texture.type = type;
  14080. texture.invertY = invertY;
  14081. texture._compression = compression;
  14082. var gl = this._gl;
  14083. var textureType = this._getWebGLTextureType(type);
  14084. var internalFormat = this._getInternalFormat(format);
  14085. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14086. var needConversion = false;
  14087. if (internalFormat === gl.RGB) {
  14088. internalFormat = gl.RGBA;
  14089. needConversion = true;
  14090. }
  14091. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14092. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14093. if (texture.width % 4 !== 0) {
  14094. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14095. }
  14096. // Data are known to be in +X +Y +Z -X -Y -Z
  14097. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14098. var faceData = data[faceIndex];
  14099. if (compression) {
  14100. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14101. }
  14102. else {
  14103. if (needConversion) {
  14104. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14105. }
  14106. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14107. }
  14108. }
  14109. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14110. if (isPot && texture.generateMipMaps && level === 0) {
  14111. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14112. }
  14113. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14114. // this.resetTextureCache();
  14115. texture.isReady = true;
  14116. };
  14117. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14118. if (compression === void 0) { compression = null; }
  14119. var gl = this._gl;
  14120. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14121. texture.isCube = true;
  14122. texture.generateMipMaps = generateMipMaps;
  14123. texture.format = format;
  14124. texture.type = type;
  14125. if (!this._doNotHandleContextLost) {
  14126. texture._bufferViewArray = data;
  14127. }
  14128. var textureType = this._getWebGLTextureType(type);
  14129. var internalFormat = this._getInternalFormat(format);
  14130. if (internalFormat === gl.RGB) {
  14131. internalFormat = gl.RGBA;
  14132. }
  14133. var width = size;
  14134. var height = width;
  14135. texture.width = width;
  14136. texture.height = height;
  14137. // Double check on POT to generate Mips.
  14138. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14139. if (!isPot) {
  14140. generateMipMaps = false;
  14141. }
  14142. // Upload data if needed. The texture won't be ready until then.
  14143. if (data) {
  14144. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14145. }
  14146. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14147. // Filters
  14148. if (data && generateMipMaps) {
  14149. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14150. }
  14151. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14152. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14153. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14154. }
  14155. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14156. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14157. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14158. }
  14159. else {
  14160. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14161. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14162. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14163. }
  14164. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14165. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14166. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14167. return texture;
  14168. };
  14169. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14170. var _this = this;
  14171. if (onLoad === void 0) { onLoad = null; }
  14172. if (onError === void 0) { onError = null; }
  14173. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14174. if (invertY === void 0) { invertY = false; }
  14175. var gl = this._gl;
  14176. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14177. scene._addPendingData(texture);
  14178. texture.url = url;
  14179. this._internalTexturesCache.push(texture);
  14180. var onerror = function (request, exception) {
  14181. scene._removePendingData(texture);
  14182. if (onError && request) {
  14183. onError(request.status + " " + request.statusText, exception);
  14184. }
  14185. };
  14186. var internalCallback = function (data) {
  14187. var width = texture.width;
  14188. var faceDataArrays = callback(data);
  14189. if (!faceDataArrays) {
  14190. return;
  14191. }
  14192. if (mipmmapGenerator) {
  14193. var textureType = _this._getWebGLTextureType(type);
  14194. var internalFormat = _this._getInternalFormat(format);
  14195. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14196. var needConversion = false;
  14197. if (internalFormat === gl.RGB) {
  14198. internalFormat = gl.RGBA;
  14199. needConversion = true;
  14200. }
  14201. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14202. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14203. var mipData = mipmmapGenerator(faceDataArrays);
  14204. for (var level = 0; level < mipData.length; level++) {
  14205. var mipSize = width >> level;
  14206. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14207. var mipFaceData = mipData[level][faceIndex];
  14208. if (needConversion) {
  14209. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14210. }
  14211. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14212. }
  14213. }
  14214. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14215. }
  14216. else {
  14217. texture.generateMipMaps = !noMipmap;
  14218. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14219. }
  14220. texture.isReady = true;
  14221. // this.resetTextureCache();
  14222. scene._removePendingData(texture);
  14223. if (onLoad) {
  14224. onLoad();
  14225. }
  14226. };
  14227. this._loadFile(url, function (data) {
  14228. internalCallback(data);
  14229. }, undefined, scene.database, true, onerror);
  14230. return texture;
  14231. };
  14232. ;
  14233. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14234. if (compression === void 0) { compression = null; }
  14235. var internalFormat = this._getInternalFormat(format);
  14236. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14237. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14238. if (!this._doNotHandleContextLost) {
  14239. texture._bufferView = data;
  14240. texture.format = format;
  14241. texture.invertY = invertY;
  14242. texture._compression = compression;
  14243. }
  14244. if (texture.width % 4 !== 0) {
  14245. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14246. }
  14247. if (compression && data) {
  14248. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14249. }
  14250. else {
  14251. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14252. }
  14253. if (texture.generateMipMaps) {
  14254. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14255. }
  14256. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14257. // this.resetTextureCache();
  14258. texture.isReady = true;
  14259. };
  14260. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14261. if (compression === void 0) { compression = null; }
  14262. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14263. texture.baseWidth = width;
  14264. texture.baseHeight = height;
  14265. texture.baseDepth = depth;
  14266. texture.width = width;
  14267. texture.height = height;
  14268. texture.depth = depth;
  14269. texture.format = format;
  14270. texture.generateMipMaps = generateMipMaps;
  14271. texture.samplingMode = samplingMode;
  14272. texture.is3D = true;
  14273. if (!this._doNotHandleContextLost) {
  14274. texture._bufferView = data;
  14275. }
  14276. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14277. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14278. // Filters
  14279. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14280. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14281. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14282. if (generateMipMaps) {
  14283. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14284. }
  14285. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14286. this._internalTexturesCache.push(texture);
  14287. return texture;
  14288. };
  14289. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14290. var gl = this._gl;
  14291. if (!gl) {
  14292. return;
  14293. }
  14294. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14296. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14297. if (!noMipmap && !isCompressed) {
  14298. gl.generateMipmap(gl.TEXTURE_2D);
  14299. }
  14300. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14301. // this.resetTextureCache();
  14302. if (scene) {
  14303. scene._removePendingData(texture);
  14304. }
  14305. texture.onLoadedObservable.notifyObservers(texture);
  14306. texture.onLoadedObservable.clear();
  14307. };
  14308. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14309. var _this = this;
  14310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14311. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14312. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14313. var gl = this._gl;
  14314. if (!gl) {
  14315. return;
  14316. }
  14317. if (!texture._webGLTexture) {
  14318. // this.resetTextureCache();
  14319. if (scene) {
  14320. scene._removePendingData(texture);
  14321. }
  14322. return;
  14323. }
  14324. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14325. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14326. texture.baseWidth = width;
  14327. texture.baseHeight = height;
  14328. texture.width = potWidth;
  14329. texture.height = potHeight;
  14330. texture.isReady = true;
  14331. if (processFunction(potWidth, potHeight, function () {
  14332. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14333. })) {
  14334. // Returning as texture needs extra async steps
  14335. return;
  14336. }
  14337. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14338. };
  14339. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14340. // Create new RGBA data container.
  14341. var rgbaData;
  14342. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14343. rgbaData = new Float32Array(width * height * 4);
  14344. }
  14345. else {
  14346. rgbaData = new Uint32Array(width * height * 4);
  14347. }
  14348. // Convert each pixel.
  14349. for (var x = 0; x < width; x++) {
  14350. for (var y = 0; y < height; y++) {
  14351. var index = (y * width + x) * 3;
  14352. var newIndex = (y * width + x) * 4;
  14353. // Map Old Value to new value.
  14354. rgbaData[newIndex + 0] = rgbData[index + 0];
  14355. rgbaData[newIndex + 1] = rgbData[index + 1];
  14356. rgbaData[newIndex + 2] = rgbData[index + 2];
  14357. // Add fully opaque alpha channel.
  14358. rgbaData[newIndex + 3] = 1;
  14359. }
  14360. }
  14361. return rgbaData;
  14362. };
  14363. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14364. var gl = this._gl;
  14365. if (texture._framebuffer) {
  14366. gl.deleteFramebuffer(texture._framebuffer);
  14367. texture._framebuffer = null;
  14368. }
  14369. if (texture._depthStencilBuffer) {
  14370. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14371. texture._depthStencilBuffer = null;
  14372. }
  14373. if (texture._MSAAFramebuffer) {
  14374. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14375. texture._MSAAFramebuffer = null;
  14376. }
  14377. if (texture._MSAARenderBuffer) {
  14378. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14379. texture._MSAARenderBuffer = null;
  14380. }
  14381. };
  14382. Engine.prototype._releaseTexture = function (texture) {
  14383. var gl = this._gl;
  14384. this._releaseFramebufferObjects(texture);
  14385. gl.deleteTexture(texture._webGLTexture);
  14386. // Unbind channels
  14387. this.unbindAllTextures();
  14388. var index = this._internalTexturesCache.indexOf(texture);
  14389. if (index !== -1) {
  14390. this._internalTexturesCache.splice(index, 1);
  14391. }
  14392. // Integrated fixed lod samplers.
  14393. if (texture._lodTextureHigh) {
  14394. texture._lodTextureHigh.dispose();
  14395. }
  14396. if (texture._lodTextureMid) {
  14397. texture._lodTextureMid.dispose();
  14398. }
  14399. if (texture._lodTextureLow) {
  14400. texture._lodTextureLow.dispose();
  14401. }
  14402. };
  14403. Engine.prototype.setProgram = function (program) {
  14404. if (this._currentProgram !== program) {
  14405. this._gl.useProgram(program);
  14406. this._currentProgram = program;
  14407. }
  14408. };
  14409. Engine.prototype.bindSamplers = function (effect) {
  14410. this.setProgram(effect.getProgram());
  14411. var samplers = effect.getSamplers();
  14412. for (var index = 0; index < samplers.length; index++) {
  14413. var uniform = effect.getUniform(samplers[index]);
  14414. if (uniform) {
  14415. this._boundUniforms[index] = uniform;
  14416. }
  14417. }
  14418. this._currentEffect = null;
  14419. };
  14420. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14421. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14422. return;
  14423. }
  14424. // Remove
  14425. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14426. // Bind last to it
  14427. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14428. // Bind to dummy
  14429. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14430. };
  14431. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14432. if (!internalTexture) {
  14433. return -1;
  14434. }
  14435. internalTexture._initialSlot = channel;
  14436. if (this.disableTextureBindingOptimization) {
  14437. if (channel !== internalTexture._designatedSlot) {
  14438. this._textureCollisions.addCount(1, false);
  14439. }
  14440. }
  14441. else {
  14442. if (channel !== internalTexture._designatedSlot) {
  14443. if (internalTexture._designatedSlot > -1) {
  14444. return internalTexture._designatedSlot;
  14445. }
  14446. else {
  14447. // No slot for this texture, let's pick a new one (if we find a free slot)
  14448. if (this._nextFreeTextureSlots.length) {
  14449. return this._nextFreeTextureSlots[0];
  14450. }
  14451. // We need to recycle the oldest bound texture, sorry.
  14452. this._textureCollisions.addCount(1, false);
  14453. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14454. }
  14455. }
  14456. }
  14457. return channel;
  14458. };
  14459. Engine.prototype._linkTrackers = function (previous, next) {
  14460. previous.next = next;
  14461. next.previous = previous;
  14462. };
  14463. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14464. var currentSlot = internalTexture._designatedSlot;
  14465. if (currentSlot === -1) {
  14466. return -1;
  14467. }
  14468. internalTexture._designatedSlot = -1;
  14469. if (this.disableTextureBindingOptimization) {
  14470. return -1;
  14471. }
  14472. // Remove from bound list
  14473. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14474. // Free the slot
  14475. this._boundTexturesCache[currentSlot] = null;
  14476. this._nextFreeTextureSlots.push(currentSlot);
  14477. return currentSlot;
  14478. };
  14479. Engine.prototype._activateCurrentTexture = function () {
  14480. if (this._currentTextureChannel !== this._activeChannel) {
  14481. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14482. this._currentTextureChannel = this._activeChannel;
  14483. }
  14484. };
  14485. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14486. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14487. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14488. this._activeChannel = texture._designatedSlot;
  14489. }
  14490. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14491. var isTextureForRendering = texture && texture._initialSlot > -1;
  14492. if (currentTextureBound !== texture) {
  14493. if (currentTextureBound) {
  14494. this._removeDesignatedSlot(currentTextureBound);
  14495. }
  14496. this._activateCurrentTexture();
  14497. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14498. this._boundTexturesCache[this._activeChannel] = texture;
  14499. if (texture) {
  14500. if (!this.disableTextureBindingOptimization) {
  14501. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14502. if (slotIndex > -1) {
  14503. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14504. }
  14505. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14506. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14507. }
  14508. texture._designatedSlot = this._activeChannel;
  14509. }
  14510. }
  14511. else if (forTextureDataUpdate) {
  14512. this._activateCurrentTexture();
  14513. }
  14514. if (isTextureForRendering && !forTextureDataUpdate) {
  14515. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14516. }
  14517. };
  14518. Engine.prototype._bindTexture = function (channel, texture) {
  14519. if (channel < 0) {
  14520. return;
  14521. }
  14522. if (texture) {
  14523. channel = this._getCorrectTextureChannel(channel, texture);
  14524. }
  14525. this._activeChannel = channel;
  14526. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14527. };
  14528. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14529. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14530. };
  14531. Engine.prototype.unbindAllTextures = function () {
  14532. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14533. this._activeChannel = channel;
  14534. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14535. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14536. if (this.webGLVersion > 1) {
  14537. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14538. }
  14539. }
  14540. };
  14541. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14542. if (channel < 0) {
  14543. return;
  14544. }
  14545. if (uniform) {
  14546. this._boundUniforms[channel] = uniform;
  14547. }
  14548. this._setTexture(channel, texture);
  14549. };
  14550. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14551. var uniform = this._boundUniforms[sourceSlot];
  14552. if (uniform._currentState === destination) {
  14553. return;
  14554. }
  14555. this._gl.uniform1i(uniform, destination);
  14556. uniform._currentState = destination;
  14557. };
  14558. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14559. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14560. // Not ready?
  14561. if (!texture) {
  14562. if (this._boundTexturesCache[channel] != null) {
  14563. this._activeChannel = channel;
  14564. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14565. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14566. if (this.webGLVersion > 1) {
  14567. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14568. }
  14569. }
  14570. return false;
  14571. }
  14572. // Video
  14573. if (texture.video) {
  14574. this._activeChannel = channel;
  14575. texture.update();
  14576. }
  14577. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14578. texture.delayLoad();
  14579. return false;
  14580. }
  14581. var internalTexture;
  14582. if (texture.isReady()) {
  14583. internalTexture = texture.getInternalTexture();
  14584. }
  14585. else if (texture.isCube) {
  14586. internalTexture = this.emptyCubeTexture;
  14587. }
  14588. else if (texture.is3D) {
  14589. internalTexture = this.emptyTexture3D;
  14590. }
  14591. else {
  14592. internalTexture = this.emptyTexture;
  14593. }
  14594. if (!isPartOfTextureArray) {
  14595. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14596. }
  14597. if (this._boundTexturesCache[channel] === internalTexture) {
  14598. this._moveBoundTextureOnTop(internalTexture);
  14599. if (!isPartOfTextureArray) {
  14600. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14601. }
  14602. return false;
  14603. }
  14604. this._activeChannel = channel;
  14605. if (internalTexture && internalTexture.is3D) {
  14606. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14607. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14608. internalTexture._cachedWrapU = texture.wrapU;
  14609. switch (texture.wrapU) {
  14610. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14611. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14612. break;
  14613. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14614. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14615. break;
  14616. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14617. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14618. break;
  14619. }
  14620. }
  14621. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14622. internalTexture._cachedWrapV = texture.wrapV;
  14623. switch (texture.wrapV) {
  14624. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14625. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14626. break;
  14627. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14628. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14629. break;
  14630. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14631. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14632. break;
  14633. }
  14634. }
  14635. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14636. internalTexture._cachedWrapR = texture.wrapR;
  14637. switch (texture.wrapR) {
  14638. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14639. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14640. break;
  14641. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14642. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14643. break;
  14644. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14645. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14646. break;
  14647. }
  14648. }
  14649. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14650. }
  14651. else if (internalTexture && internalTexture.isCube) {
  14652. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14653. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14654. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14655. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14656. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14657. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14658. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14659. }
  14660. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14661. }
  14662. else {
  14663. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14664. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14665. internalTexture._cachedWrapU = texture.wrapU;
  14666. switch (texture.wrapU) {
  14667. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14668. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14669. break;
  14670. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14671. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14672. break;
  14673. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14674. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14675. break;
  14676. }
  14677. }
  14678. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14679. internalTexture._cachedWrapV = texture.wrapV;
  14680. switch (texture.wrapV) {
  14681. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14682. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14683. break;
  14684. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14685. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14686. break;
  14687. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14688. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14689. break;
  14690. }
  14691. }
  14692. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14693. }
  14694. return true;
  14695. };
  14696. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14697. if (channel < 0 || !uniform) {
  14698. return;
  14699. }
  14700. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14701. this._textureUnits = new Int32Array(textures.length);
  14702. }
  14703. for (var i = 0; i < textures.length; i++) {
  14704. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14705. }
  14706. this._gl.uniform1iv(uniform, this._textureUnits);
  14707. for (var index = 0; index < textures.length; index++) {
  14708. this._setTexture(this._textureUnits[index], textures[index], true);
  14709. }
  14710. };
  14711. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14712. var internalTexture = texture.getInternalTexture();
  14713. if (!internalTexture) {
  14714. return;
  14715. }
  14716. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14717. var value = texture.anisotropicFilteringLevel;
  14718. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14719. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14720. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14721. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14722. }
  14723. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14724. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14725. internalTexture._cachedAnisotropicFilteringLevel = value;
  14726. }
  14727. };
  14728. Engine.prototype.readPixels = function (x, y, width, height) {
  14729. var data = new Uint8Array(height * width * 4);
  14730. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14731. return data;
  14732. };
  14733. /**
  14734. * Add an externaly attached data from its key.
  14735. * This method call will fail and return false, if such key already exists.
  14736. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14737. * @param key the unique key that identifies the data
  14738. * @param data the data object to associate to the key for this Engine instance
  14739. * @return true if no such key were already present and the data was added successfully, false otherwise
  14740. */
  14741. Engine.prototype.addExternalData = function (key, data) {
  14742. if (!this._externalData) {
  14743. this._externalData = new BABYLON.StringDictionary();
  14744. }
  14745. return this._externalData.add(key, data);
  14746. };
  14747. /**
  14748. * Get an externaly attached data from its key
  14749. * @param key the unique key that identifies the data
  14750. * @return the associated data, if present (can be null), or undefined if not present
  14751. */
  14752. Engine.prototype.getExternalData = function (key) {
  14753. if (!this._externalData) {
  14754. this._externalData = new BABYLON.StringDictionary();
  14755. }
  14756. return this._externalData.get(key);
  14757. };
  14758. /**
  14759. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14760. * @param key the unique key that identifies the data
  14761. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14762. * @return the associated data, can be null if the factory returned null.
  14763. */
  14764. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14765. if (!this._externalData) {
  14766. this._externalData = new BABYLON.StringDictionary();
  14767. }
  14768. return this._externalData.getOrAddWithFactory(key, factory);
  14769. };
  14770. /**
  14771. * Remove an externaly attached data from the Engine instance
  14772. * @param key the unique key that identifies the data
  14773. * @return true if the data was successfully removed, false if it doesn't exist
  14774. */
  14775. Engine.prototype.removeExternalData = function (key) {
  14776. if (!this._externalData) {
  14777. this._externalData = new BABYLON.StringDictionary();
  14778. }
  14779. return this._externalData.remove(key);
  14780. };
  14781. Engine.prototype.unbindAllAttributes = function () {
  14782. if (this._mustWipeVertexAttributes) {
  14783. this._mustWipeVertexAttributes = false;
  14784. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14785. this._gl.disableVertexAttribArray(i);
  14786. this._vertexAttribArraysEnabled[i] = false;
  14787. this._currentBufferPointers[i].active = false;
  14788. }
  14789. return;
  14790. }
  14791. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14792. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14793. continue;
  14794. }
  14795. this._gl.disableVertexAttribArray(i);
  14796. this._vertexAttribArraysEnabled[i] = false;
  14797. this._currentBufferPointers[i].active = false;
  14798. }
  14799. };
  14800. Engine.prototype.releaseEffects = function () {
  14801. for (var name in this._compiledEffects) {
  14802. this._deleteProgram(this._compiledEffects[name]._program);
  14803. }
  14804. this._compiledEffects = {};
  14805. };
  14806. // Dispose
  14807. Engine.prototype.dispose = function () {
  14808. this.hideLoadingUI();
  14809. this.stopRenderLoop();
  14810. // Release postProcesses
  14811. while (this.postProcesses.length) {
  14812. this.postProcesses[0].dispose();
  14813. }
  14814. // Empty texture
  14815. if (this._emptyTexture) {
  14816. this._releaseTexture(this._emptyTexture);
  14817. this._emptyTexture = null;
  14818. }
  14819. if (this._emptyCubeTexture) {
  14820. this._releaseTexture(this._emptyCubeTexture);
  14821. this._emptyCubeTexture = null;
  14822. }
  14823. // Rescale PP
  14824. if (this._rescalePostProcess) {
  14825. this._rescalePostProcess.dispose();
  14826. }
  14827. // Release scenes
  14828. while (this.scenes.length) {
  14829. this.scenes[0].dispose();
  14830. }
  14831. // Release audio engine
  14832. if (Engine.audioEngine) {
  14833. Engine.audioEngine.dispose();
  14834. }
  14835. // Release effects
  14836. this.releaseEffects();
  14837. // Unbind
  14838. this.unbindAllAttributes();
  14839. if (this._dummyFramebuffer) {
  14840. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14841. }
  14842. //WebVR
  14843. this.disableVR();
  14844. // Events
  14845. if (BABYLON.Tools.IsWindowObjectExist()) {
  14846. window.removeEventListener("blur", this._onBlur);
  14847. window.removeEventListener("focus", this._onFocus);
  14848. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14849. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14850. if (this._renderingCanvas) {
  14851. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14852. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14853. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  14854. if (!this._doNotHandleContextLost) {
  14855. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14856. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14857. }
  14858. }
  14859. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14860. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14861. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14862. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14863. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14864. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14865. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14866. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14867. if (this._onVrDisplayConnect) {
  14868. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14869. if (this._onVrDisplayDisconnect) {
  14870. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14871. }
  14872. if (this._onVrDisplayPresentChange) {
  14873. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14874. }
  14875. this._onVrDisplayConnect = null;
  14876. this._onVrDisplayDisconnect = null;
  14877. }
  14878. }
  14879. // Remove from Instances
  14880. var index = Engine.Instances.indexOf(this);
  14881. if (index >= 0) {
  14882. Engine.Instances.splice(index, 1);
  14883. }
  14884. this._workingCanvas = null;
  14885. this._workingContext = null;
  14886. this._currentBufferPointers = [];
  14887. this._renderingCanvas = null;
  14888. this._currentProgram = null;
  14889. this._bindedRenderFunction = null;
  14890. this.onResizeObservable.clear();
  14891. this.onCanvasBlurObservable.clear();
  14892. this.onCanvasFocusObservable.clear();
  14893. this.onCanvasPointerOutObservable.clear();
  14894. this.onBeginFrameObservable.clear();
  14895. this.onEndFrameObservable.clear();
  14896. BABYLON.Effect.ResetCache();
  14897. // Abort active requests
  14898. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14899. var request = _a[_i];
  14900. request.abort();
  14901. }
  14902. };
  14903. // Loading screen
  14904. Engine.prototype.displayLoadingUI = function () {
  14905. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14906. return;
  14907. }
  14908. var loadingScreen = this.loadingScreen;
  14909. if (loadingScreen) {
  14910. loadingScreen.displayLoadingUI();
  14911. }
  14912. };
  14913. Engine.prototype.hideLoadingUI = function () {
  14914. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14915. return;
  14916. }
  14917. var loadingScreen = this.loadingScreen;
  14918. if (loadingScreen) {
  14919. loadingScreen.hideLoadingUI();
  14920. }
  14921. };
  14922. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14923. get: function () {
  14924. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14925. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14926. return this._loadingScreen;
  14927. },
  14928. set: function (loadingScreen) {
  14929. this._loadingScreen = loadingScreen;
  14930. },
  14931. enumerable: true,
  14932. configurable: true
  14933. });
  14934. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14935. set: function (text) {
  14936. this.loadingScreen.loadingUIText = text;
  14937. },
  14938. enumerable: true,
  14939. configurable: true
  14940. });
  14941. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14942. set: function (color) {
  14943. this.loadingScreen.loadingUIBackgroundColor = color;
  14944. },
  14945. enumerable: true,
  14946. configurable: true
  14947. });
  14948. Engine.prototype.attachContextLostEvent = function (callback) {
  14949. if (this._renderingCanvas) {
  14950. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14951. }
  14952. };
  14953. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14954. if (this._renderingCanvas) {
  14955. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14956. }
  14957. };
  14958. Engine.prototype.getVertexShaderSource = function (program) {
  14959. var shaders = this._gl.getAttachedShaders(program);
  14960. if (!shaders) {
  14961. return null;
  14962. }
  14963. return this._gl.getShaderSource(shaders[0]);
  14964. };
  14965. Engine.prototype.getFragmentShaderSource = function (program) {
  14966. var shaders = this._gl.getAttachedShaders(program);
  14967. if (!shaders) {
  14968. return null;
  14969. }
  14970. return this._gl.getShaderSource(shaders[1]);
  14971. };
  14972. Engine.prototype.getError = function () {
  14973. return this._gl.getError();
  14974. };
  14975. // FPS
  14976. Engine.prototype.getFps = function () {
  14977. return this._fps;
  14978. };
  14979. Engine.prototype.getDeltaTime = function () {
  14980. return this._deltaTime;
  14981. };
  14982. Engine.prototype._measureFps = function () {
  14983. this._performanceMonitor.sampleFrame();
  14984. this._fps = this._performanceMonitor.averageFPS;
  14985. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14986. };
  14987. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14988. if (faceIndex === void 0) { faceIndex = -1; }
  14989. var gl = this._gl;
  14990. if (!this._dummyFramebuffer) {
  14991. var dummy = gl.createFramebuffer();
  14992. if (!dummy) {
  14993. throw new Error("Unable to create dummy framebuffer");
  14994. }
  14995. this._dummyFramebuffer = dummy;
  14996. }
  14997. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14998. if (faceIndex > -1) {
  14999. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15000. }
  15001. else {
  15002. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15003. }
  15004. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15005. var buffer;
  15006. switch (readType) {
  15007. case gl.UNSIGNED_BYTE:
  15008. buffer = new Uint8Array(4 * width * height);
  15009. readType = gl.UNSIGNED_BYTE;
  15010. break;
  15011. default:
  15012. buffer = new Float32Array(4 * width * height);
  15013. readType = gl.FLOAT;
  15014. break;
  15015. }
  15016. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15017. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15018. return buffer;
  15019. };
  15020. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15021. if (this._webGLVersion > 1) {
  15022. return this._caps.colorBufferFloat;
  15023. }
  15024. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15025. };
  15026. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15027. if (this._webGLVersion > 1) {
  15028. return this._caps.colorBufferFloat;
  15029. }
  15030. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15031. };
  15032. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15033. Engine.prototype._canRenderToFramebuffer = function (type) {
  15034. var gl = this._gl;
  15035. //clear existing errors
  15036. while (gl.getError() !== gl.NO_ERROR) { }
  15037. var successful = true;
  15038. var texture = gl.createTexture();
  15039. gl.bindTexture(gl.TEXTURE_2D, texture);
  15040. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15041. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15042. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15043. var fb = gl.createFramebuffer();
  15044. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15045. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15046. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15047. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15048. successful = successful && (gl.getError() === gl.NO_ERROR);
  15049. //try render by clearing frame buffer's color buffer
  15050. if (successful) {
  15051. gl.clear(gl.COLOR_BUFFER_BIT);
  15052. successful = successful && (gl.getError() === gl.NO_ERROR);
  15053. }
  15054. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15055. if (successful) {
  15056. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15057. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15058. var readFormat = gl.RGBA;
  15059. var readType = gl.UNSIGNED_BYTE;
  15060. var buffer = new Uint8Array(4);
  15061. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15062. successful = successful && (gl.getError() === gl.NO_ERROR);
  15063. }
  15064. //clean up
  15065. gl.deleteTexture(texture);
  15066. gl.deleteFramebuffer(fb);
  15067. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15068. //clear accumulated errors
  15069. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15070. return successful;
  15071. };
  15072. Engine.prototype._getWebGLTextureType = function (type) {
  15073. if (type === Engine.TEXTURETYPE_FLOAT) {
  15074. return this._gl.FLOAT;
  15075. }
  15076. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15077. // Add Half Float Constant.
  15078. return this._gl.HALF_FLOAT_OES;
  15079. }
  15080. return this._gl.UNSIGNED_BYTE;
  15081. };
  15082. ;
  15083. /** @ignore */
  15084. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15085. if (this._webGLVersion === 1) {
  15086. return this._gl.RGBA;
  15087. }
  15088. if (type === Engine.TEXTURETYPE_FLOAT) {
  15089. if (format) {
  15090. switch (format) {
  15091. case Engine.TEXTUREFORMAT_R32F:
  15092. return this._gl.R32F;
  15093. case Engine.TEXTUREFORMAT_RG32F:
  15094. return this._gl.RG32F;
  15095. case Engine.TEXTUREFORMAT_RGB32F:
  15096. return this._gl.RGB32F;
  15097. }
  15098. }
  15099. return this._gl.RGBA32F;
  15100. }
  15101. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15102. return this._gl.RGBA16F;
  15103. }
  15104. return this._gl.RGBA;
  15105. };
  15106. ;
  15107. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15108. if (type === Engine.TEXTURETYPE_FLOAT) {
  15109. return this._gl.RGBA32F;
  15110. }
  15111. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15112. return this._gl.RGBA16F;
  15113. }
  15114. return this._gl.RGBA8;
  15115. };
  15116. ;
  15117. Engine.prototype.createQuery = function () {
  15118. return this._gl.createQuery();
  15119. };
  15120. Engine.prototype.deleteQuery = function (query) {
  15121. this._gl.deleteQuery(query);
  15122. return this;
  15123. };
  15124. Engine.prototype.isQueryResultAvailable = function (query) {
  15125. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15126. };
  15127. Engine.prototype.getQueryResult = function (query) {
  15128. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15129. };
  15130. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15131. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15132. this._gl.beginQuery(glAlgorithm, query);
  15133. return this;
  15134. };
  15135. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15136. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15137. this._gl.endQuery(glAlgorithm);
  15138. return this;
  15139. };
  15140. /* Time queries */
  15141. Engine.prototype._createTimeQuery = function () {
  15142. var timerQuery = this._caps.timerQuery;
  15143. if (timerQuery.createQueryEXT) {
  15144. return timerQuery.createQueryEXT();
  15145. }
  15146. return this.createQuery();
  15147. };
  15148. Engine.prototype._deleteTimeQuery = function (query) {
  15149. var timerQuery = this._caps.timerQuery;
  15150. if (timerQuery.deleteQueryEXT) {
  15151. timerQuery.deleteQueryEXT(query);
  15152. return;
  15153. }
  15154. this.deleteQuery(query);
  15155. };
  15156. Engine.prototype._getTimeQueryResult = function (query) {
  15157. var timerQuery = this._caps.timerQuery;
  15158. if (timerQuery.getQueryObjectEXT) {
  15159. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15160. }
  15161. return this.getQueryResult(query);
  15162. };
  15163. Engine.prototype._getTimeQueryAvailability = function (query) {
  15164. var timerQuery = this._caps.timerQuery;
  15165. if (timerQuery.getQueryObjectEXT) {
  15166. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15167. }
  15168. return this.isQueryResultAvailable(query);
  15169. };
  15170. Engine.prototype.startTimeQuery = function () {
  15171. var timerQuery = this._caps.timerQuery;
  15172. if (!timerQuery) {
  15173. return null;
  15174. }
  15175. var token = new BABYLON._TimeToken();
  15176. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15177. if (this._caps.canUseTimestampForTimerQuery) {
  15178. token._startTimeQuery = this._createTimeQuery();
  15179. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15180. }
  15181. else {
  15182. if (this._currentNonTimestampToken) {
  15183. return this._currentNonTimestampToken;
  15184. }
  15185. token._timeElapsedQuery = this._createTimeQuery();
  15186. if (timerQuery.beginQueryEXT) {
  15187. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15188. }
  15189. else {
  15190. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15191. }
  15192. this._currentNonTimestampToken = token;
  15193. }
  15194. return token;
  15195. };
  15196. Engine.prototype.endTimeQuery = function (token) {
  15197. var timerQuery = this._caps.timerQuery;
  15198. if (!timerQuery || !token) {
  15199. return -1;
  15200. }
  15201. if (this._caps.canUseTimestampForTimerQuery) {
  15202. if (!token._startTimeQuery) {
  15203. return -1;
  15204. }
  15205. if (!token._endTimeQuery) {
  15206. token._endTimeQuery = this._createTimeQuery();
  15207. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15208. }
  15209. }
  15210. else if (!token._timeElapsedQueryEnded) {
  15211. if (!token._timeElapsedQuery) {
  15212. return -1;
  15213. }
  15214. if (timerQuery.endQueryEXT) {
  15215. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15216. }
  15217. else {
  15218. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15219. }
  15220. token._timeElapsedQueryEnded = true;
  15221. }
  15222. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15223. var available = false;
  15224. if (token._endTimeQuery) {
  15225. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15226. }
  15227. else if (token._timeElapsedQuery) {
  15228. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15229. }
  15230. if (available && !disjoint) {
  15231. var result = 0;
  15232. if (this._caps.canUseTimestampForTimerQuery) {
  15233. if (!token._startTimeQuery || !token._endTimeQuery) {
  15234. return -1;
  15235. }
  15236. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15237. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15238. result = timeEnd - timeStart;
  15239. this._deleteTimeQuery(token._startTimeQuery);
  15240. this._deleteTimeQuery(token._endTimeQuery);
  15241. token._startTimeQuery = null;
  15242. token._endTimeQuery = null;
  15243. }
  15244. else {
  15245. if (!token._timeElapsedQuery) {
  15246. return -1;
  15247. }
  15248. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15249. this._deleteTimeQuery(token._timeElapsedQuery);
  15250. token._timeElapsedQuery = null;
  15251. token._timeElapsedQueryEnded = false;
  15252. this._currentNonTimestampToken = null;
  15253. }
  15254. return result;
  15255. }
  15256. return -1;
  15257. };
  15258. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15259. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15260. };
  15261. // Transform feedback
  15262. Engine.prototype.createTransformFeedback = function () {
  15263. return this._gl.createTransformFeedback();
  15264. };
  15265. Engine.prototype.deleteTransformFeedback = function (value) {
  15266. this._gl.deleteTransformFeedback(value);
  15267. };
  15268. Engine.prototype.bindTransformFeedback = function (value) {
  15269. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15270. };
  15271. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15272. if (usePoints === void 0) { usePoints = true; }
  15273. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15274. };
  15275. Engine.prototype.endTransformFeedback = function () {
  15276. this._gl.endTransformFeedback();
  15277. };
  15278. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15279. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15280. };
  15281. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15282. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15283. };
  15284. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15285. var _this = this;
  15286. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15287. this._activeRequests.push(request);
  15288. request.onCompleteObservable.add(function (request) {
  15289. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15290. });
  15291. return request;
  15292. };
  15293. /** @ignore */
  15294. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15295. var _this = this;
  15296. return new Promise(function (resolve, reject) {
  15297. _this._loadFile(url, function (data) {
  15298. resolve(data);
  15299. }, undefined, database, useArrayBuffer, function (request, exception) {
  15300. reject(exception);
  15301. });
  15302. });
  15303. };
  15304. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15305. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15306. var onload = function (data) {
  15307. loadedFiles[index] = data;
  15308. loadedFiles._internalCount++;
  15309. if (loadedFiles._internalCount === 6) {
  15310. onfinish(loadedFiles);
  15311. }
  15312. };
  15313. var onerror = function (request, exception) {
  15314. if (onErrorCallBack && request) {
  15315. onErrorCallBack(request.status + " " + request.statusText, exception);
  15316. }
  15317. };
  15318. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15319. };
  15320. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15321. if (onError === void 0) { onError = null; }
  15322. var loadedFiles = [];
  15323. loadedFiles._internalCount = 0;
  15324. for (var index = 0; index < 6; index++) {
  15325. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15326. }
  15327. };
  15328. // Statics
  15329. Engine.isSupported = function () {
  15330. try {
  15331. var tempcanvas = document.createElement("canvas");
  15332. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15333. return gl != null && !!window.WebGLRenderingContext;
  15334. }
  15335. catch (e) {
  15336. return false;
  15337. }
  15338. };
  15339. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15340. Engine.ExceptionList = [
  15341. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15342. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15343. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15344. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15345. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15346. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15347. ];
  15348. Engine.Instances = new Array();
  15349. // Const statics
  15350. Engine._ALPHA_DISABLE = 0;
  15351. Engine._ALPHA_ADD = 1;
  15352. Engine._ALPHA_COMBINE = 2;
  15353. Engine._ALPHA_SUBTRACT = 3;
  15354. Engine._ALPHA_MULTIPLY = 4;
  15355. Engine._ALPHA_MAXIMIZED = 5;
  15356. Engine._ALPHA_ONEONE = 6;
  15357. Engine._ALPHA_PREMULTIPLIED = 7;
  15358. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15359. Engine._ALPHA_INTERPOLATE = 9;
  15360. Engine._ALPHA_SCREENMODE = 10;
  15361. Engine._DELAYLOADSTATE_NONE = 0;
  15362. Engine._DELAYLOADSTATE_LOADED = 1;
  15363. Engine._DELAYLOADSTATE_LOADING = 2;
  15364. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15365. Engine._TEXTUREFORMAT_ALPHA = 0;
  15366. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15367. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15368. Engine._TEXTUREFORMAT_RGB = 4;
  15369. Engine._TEXTUREFORMAT_RGBA = 5;
  15370. Engine._TEXTUREFORMAT_R32F = 6;
  15371. Engine._TEXTUREFORMAT_RG32F = 7;
  15372. Engine._TEXTUREFORMAT_RGB32F = 8;
  15373. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15374. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15375. Engine._TEXTURETYPE_FLOAT = 1;
  15376. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15377. // Depht or Stencil test Constants.
  15378. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15379. 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.
  15380. 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.
  15381. 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.
  15382. 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.
  15383. 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.
  15384. 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.
  15385. 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.
  15386. // Stencil Actions Constants.
  15387. Engine._KEEP = 0x1E00;
  15388. Engine._REPLACE = 0x1E01;
  15389. Engine._INCR = 0x1E02;
  15390. Engine._DECR = 0x1E03;
  15391. Engine._INVERT = 0x150A;
  15392. Engine._INCR_WRAP = 0x8507;
  15393. Engine._DECR_WRAP = 0x8508;
  15394. // Texture rescaling mode
  15395. Engine._SCALEMODE_FLOOR = 1;
  15396. Engine._SCALEMODE_NEAREST = 2;
  15397. Engine._SCALEMODE_CEILING = 3;
  15398. // Updatable statics so stick with vars here
  15399. Engine.CollisionsEpsilon = 0.001;
  15400. Engine.CodeRepository = "src/";
  15401. Engine.ShadersRepository = "src/Shaders/";
  15402. return Engine;
  15403. }());
  15404. BABYLON.Engine = Engine;
  15405. })(BABYLON || (BABYLON = {}));
  15406. //# sourceMappingURL=babylon.engine.js.map
  15407. var BABYLON;
  15408. (function (BABYLON) {
  15409. /**
  15410. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15411. */
  15412. var Node = /** @class */ (function () {
  15413. /**
  15414. * Creates a new Node
  15415. * @param {string} name - the name and id to be given to this node
  15416. * @param {BABYLON.Scene} the scene this node will be added to
  15417. */
  15418. function Node(name, scene) {
  15419. if (scene === void 0) { scene = null; }
  15420. /**
  15421. * Gets or sets a string used to store user defined state for the node
  15422. */
  15423. this.state = "";
  15424. /**
  15425. * Gets or sets an object used to store user defined information for the node
  15426. */
  15427. this.metadata = null;
  15428. /**
  15429. * Gets or sets a boolean used to define if the node must be serialized
  15430. */
  15431. this.doNotSerialize = false;
  15432. /** @ignore */
  15433. this._isDisposed = false;
  15434. /**
  15435. * Gets a list of {BABYLON.Animation} associated with the node
  15436. */
  15437. this.animations = new Array();
  15438. this._ranges = {};
  15439. this._isEnabled = true;
  15440. this._isReady = true;
  15441. /** @ignore */
  15442. this._currentRenderId = -1;
  15443. this._parentRenderId = -1;
  15444. this._animationPropertiesOverride = null;
  15445. /**
  15446. * An event triggered when the mesh is disposed
  15447. * @type {BABYLON.Observable}
  15448. */
  15449. this.onDisposeObservable = new BABYLON.Observable();
  15450. // Behaviors
  15451. this._behaviors = new Array();
  15452. this.name = name;
  15453. this.id = name;
  15454. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15455. this.uniqueId = this._scene.getUniqueId();
  15456. this._initCache();
  15457. }
  15458. /**
  15459. * Gets a boolean indicating if the node has been disposed
  15460. * @returns true if the node was disposed
  15461. */
  15462. Node.prototype.isDisposed = function () {
  15463. return this._isDisposed;
  15464. };
  15465. Object.defineProperty(Node.prototype, "parent", {
  15466. get: function () {
  15467. return this._parentNode;
  15468. },
  15469. /**
  15470. * Gets or sets the parent of the node
  15471. */
  15472. set: function (parent) {
  15473. if (this._parentNode === parent) {
  15474. return;
  15475. }
  15476. // Remove self from list of children of parent
  15477. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15478. var index = this._parentNode._children.indexOf(this);
  15479. if (index !== -1) {
  15480. this._parentNode._children.splice(index, 1);
  15481. }
  15482. }
  15483. // Store new parent
  15484. this._parentNode = parent;
  15485. // Add as child to new parent
  15486. if (this._parentNode) {
  15487. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15488. this._parentNode._children = new Array();
  15489. }
  15490. this._parentNode._children.push(this);
  15491. }
  15492. },
  15493. enumerable: true,
  15494. configurable: true
  15495. });
  15496. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15497. /**
  15498. * Gets or sets the animation properties override
  15499. */
  15500. get: function () {
  15501. return this._animationPropertiesOverride;
  15502. },
  15503. set: function (value) {
  15504. this._animationPropertiesOverride = value;
  15505. },
  15506. enumerable: true,
  15507. configurable: true
  15508. });
  15509. /**
  15510. * Gets a string idenfifying the name of the class
  15511. * @returns "Node" string
  15512. */
  15513. Node.prototype.getClassName = function () {
  15514. return "Node";
  15515. };
  15516. Object.defineProperty(Node.prototype, "onDispose", {
  15517. /**
  15518. * Sets a callback that will be raised when the node will be disposed
  15519. */
  15520. set: function (callback) {
  15521. if (this._onDisposeObserver) {
  15522. this.onDisposeObservable.remove(this._onDisposeObserver);
  15523. }
  15524. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15525. },
  15526. enumerable: true,
  15527. configurable: true
  15528. });
  15529. /**
  15530. * Gets the scene of the node
  15531. * @returns a {BABYLON.Scene}
  15532. */
  15533. Node.prototype.getScene = function () {
  15534. return this._scene;
  15535. };
  15536. /**
  15537. * Gets the engine of the node
  15538. * @returns a {BABYLON.Engine}
  15539. */
  15540. Node.prototype.getEngine = function () {
  15541. return this._scene.getEngine();
  15542. };
  15543. /**
  15544. * Attach a behavior to the node
  15545. * @see http://doc.babylonjs.com/features/behaviour
  15546. * @param behavior defines the behavior to attach
  15547. * @returns the current Node
  15548. */
  15549. Node.prototype.addBehavior = function (behavior) {
  15550. var _this = this;
  15551. var index = this._behaviors.indexOf(behavior);
  15552. if (index !== -1) {
  15553. return this;
  15554. }
  15555. behavior.init();
  15556. if (this._scene.isLoading) {
  15557. // We defer the attach when the scene will be loaded
  15558. var observer = this._scene.onDataLoadedObservable.add(function () {
  15559. behavior.attach(_this);
  15560. setTimeout(function () {
  15561. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15562. _this._scene.onDataLoadedObservable.remove(observer);
  15563. }, 0);
  15564. });
  15565. }
  15566. else {
  15567. behavior.attach(this);
  15568. }
  15569. this._behaviors.push(behavior);
  15570. return this;
  15571. };
  15572. /**
  15573. * Remove an attached behavior
  15574. * @see http://doc.babylonjs.com/features/behaviour
  15575. * @param behavior defines the behavior to attach
  15576. * @returns the current Node
  15577. */
  15578. Node.prototype.removeBehavior = function (behavior) {
  15579. var index = this._behaviors.indexOf(behavior);
  15580. if (index === -1) {
  15581. return this;
  15582. }
  15583. this._behaviors[index].detach();
  15584. this._behaviors.splice(index, 1);
  15585. return this;
  15586. };
  15587. Object.defineProperty(Node.prototype, "behaviors", {
  15588. /**
  15589. * Gets the list of attached behaviors
  15590. * @see http://doc.babylonjs.com/features/behaviour
  15591. */
  15592. get: function () {
  15593. return this._behaviors;
  15594. },
  15595. enumerable: true,
  15596. configurable: true
  15597. });
  15598. /**
  15599. * Gets an attached behavior by name
  15600. * @param name defines the name of the behavior to look for
  15601. * @see http://doc.babylonjs.com/features/behaviour
  15602. * @returns null if behavior was not found else the requested behavior
  15603. */
  15604. Node.prototype.getBehaviorByName = function (name) {
  15605. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15606. var behavior = _a[_i];
  15607. if (behavior.name === name) {
  15608. return behavior;
  15609. }
  15610. }
  15611. return null;
  15612. };
  15613. /**
  15614. * Returns the world matrix of the node
  15615. * @returns a matrix containing the node's world matrix
  15616. */
  15617. Node.prototype.getWorldMatrix = function () {
  15618. return BABYLON.Matrix.Identity();
  15619. };
  15620. // override it in derived class if you add new variables to the cache
  15621. // and call the parent class method
  15622. /** @ignore */
  15623. Node.prototype._initCache = function () {
  15624. this._cache = {};
  15625. this._cache.parent = undefined;
  15626. };
  15627. /** @ignore */
  15628. Node.prototype.updateCache = function (force) {
  15629. if (!force && this.isSynchronized())
  15630. return;
  15631. this._cache.parent = this.parent;
  15632. this._updateCache();
  15633. };
  15634. // override it in derived class if you add new variables to the cache
  15635. // and call the parent class method if !ignoreParentClass
  15636. /** @ignore */
  15637. Node.prototype._updateCache = function (ignoreParentClass) {
  15638. };
  15639. // override it in derived class if you add new variables to the cache
  15640. /** @ignore */
  15641. Node.prototype._isSynchronized = function () {
  15642. return true;
  15643. };
  15644. /** @ignore */
  15645. Node.prototype._markSyncedWithParent = function () {
  15646. if (this.parent) {
  15647. this._parentRenderId = this.parent._currentRenderId;
  15648. }
  15649. };
  15650. /** @ignore */
  15651. Node.prototype.isSynchronizedWithParent = function () {
  15652. if (!this.parent) {
  15653. return true;
  15654. }
  15655. if (this._parentRenderId !== this.parent._currentRenderId) {
  15656. return false;
  15657. }
  15658. return this.parent.isSynchronized();
  15659. };
  15660. /** @ignore */
  15661. Node.prototype.isSynchronized = function (updateCache) {
  15662. var check = this.hasNewParent();
  15663. check = check || !this.isSynchronizedWithParent();
  15664. check = check || !this._isSynchronized();
  15665. if (updateCache)
  15666. this.updateCache(true);
  15667. return !check;
  15668. };
  15669. /** @ignore */
  15670. Node.prototype.hasNewParent = function (update) {
  15671. if (this._cache.parent === this.parent)
  15672. return false;
  15673. if (update)
  15674. this._cache.parent = this.parent;
  15675. return true;
  15676. };
  15677. /**
  15678. * Is this node ready to be used/rendered
  15679. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15680. * @return true if the node is ready
  15681. */
  15682. Node.prototype.isReady = function (completeCheck) {
  15683. if (completeCheck === void 0) { completeCheck = false; }
  15684. return this._isReady;
  15685. };
  15686. /**
  15687. * Is this node enabled?
  15688. * 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
  15689. * @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
  15690. * @return whether this node (and its parent) is enabled
  15691. * @see setEnabled
  15692. */
  15693. Node.prototype.isEnabled = function (checkAncestors) {
  15694. if (checkAncestors === void 0) { checkAncestors = true; }
  15695. if (checkAncestors === false) {
  15696. return this._isEnabled;
  15697. }
  15698. if (this._isEnabled === false) {
  15699. return false;
  15700. }
  15701. if (this.parent !== undefined && this.parent !== null) {
  15702. return this.parent.isEnabled(checkAncestors);
  15703. }
  15704. return true;
  15705. };
  15706. /**
  15707. * Set the enabled state of this node
  15708. * @param value defines the new enabled state
  15709. * @see isEnabled
  15710. */
  15711. Node.prototype.setEnabled = function (value) {
  15712. this._isEnabled = value;
  15713. };
  15714. /**
  15715. * Is this node a descendant of the given node?
  15716. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15717. * @param ancestor defines the parent node to inspect
  15718. * @see parent
  15719. * @returns a boolean indicating if this node is a descendant of the given node
  15720. */
  15721. Node.prototype.isDescendantOf = function (ancestor) {
  15722. if (this.parent) {
  15723. if (this.parent === ancestor) {
  15724. return true;
  15725. }
  15726. return this.parent.isDescendantOf(ancestor);
  15727. }
  15728. return false;
  15729. };
  15730. /** @ignore */
  15731. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15732. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15733. if (!this._children) {
  15734. return;
  15735. }
  15736. for (var index = 0; index < this._children.length; index++) {
  15737. var item = this._children[index];
  15738. if (!predicate || predicate(item)) {
  15739. results.push(item);
  15740. }
  15741. if (!directDescendantsOnly) {
  15742. item._getDescendants(results, false, predicate);
  15743. }
  15744. }
  15745. };
  15746. /**
  15747. * Will return all nodes that have this node as ascendant
  15748. * @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
  15749. * @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
  15750. * @return all children nodes of all types
  15751. */
  15752. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15753. var results = new Array();
  15754. this._getDescendants(results, directDescendantsOnly, predicate);
  15755. return results;
  15756. };
  15757. /**
  15758. * Get all child-meshes of this node
  15759. * @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
  15760. * @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
  15761. * @returns an array of {BABYLON.AbstractMesh}
  15762. */
  15763. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15764. var results = [];
  15765. this._getDescendants(results, directDescendantsOnly, function (node) {
  15766. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15767. });
  15768. return results;
  15769. };
  15770. /**
  15771. * Get all child-transformNodes of this node
  15772. * @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
  15773. * @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
  15774. * @returns an array of {BABYLON.TransformNode}
  15775. */
  15776. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15777. var results = [];
  15778. this._getDescendants(results, directDescendantsOnly, function (node) {
  15779. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15780. });
  15781. return results;
  15782. };
  15783. /**
  15784. * Get all direct children of this node
  15785. * @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
  15786. * @returns an array of {BABYLON.Node}
  15787. */
  15788. Node.prototype.getChildren = function (predicate) {
  15789. return this.getDescendants(true, predicate);
  15790. };
  15791. /** @ignore */
  15792. Node.prototype._setReady = function (state) {
  15793. if (state === this._isReady) {
  15794. return;
  15795. }
  15796. if (!state) {
  15797. this._isReady = false;
  15798. return;
  15799. }
  15800. this._isReady = true;
  15801. if (this.onReady) {
  15802. this.onReady(this);
  15803. }
  15804. };
  15805. /**
  15806. * Get an animation by name
  15807. * @param name defines the name of the animation to look for
  15808. * @returns null if not found else the requested animation
  15809. */
  15810. Node.prototype.getAnimationByName = function (name) {
  15811. for (var i = 0; i < this.animations.length; i++) {
  15812. var animation = this.animations[i];
  15813. if (animation.name === name) {
  15814. return animation;
  15815. }
  15816. }
  15817. return null;
  15818. };
  15819. /**
  15820. * Creates an animation range for this node
  15821. * @param name defines the name of the range
  15822. * @param from defines the starting key
  15823. * @param to defines the end key
  15824. */
  15825. Node.prototype.createAnimationRange = function (name, from, to) {
  15826. // check name not already in use
  15827. if (!this._ranges[name]) {
  15828. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15829. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15830. if (this.animations[i]) {
  15831. this.animations[i].createRange(name, from, to);
  15832. }
  15833. }
  15834. }
  15835. };
  15836. /**
  15837. * Delete a specific animation range
  15838. * @param name defines the name of the range to delete
  15839. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15840. */
  15841. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15842. if (deleteFrames === void 0) { deleteFrames = true; }
  15843. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15844. if (this.animations[i]) {
  15845. this.animations[i].deleteRange(name, deleteFrames);
  15846. }
  15847. }
  15848. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15849. };
  15850. /**
  15851. * Get an animation range by name
  15852. * @param name defines the name of the animation range to look for
  15853. * @returns null if not found else the requested animation range
  15854. */
  15855. Node.prototype.getAnimationRange = function (name) {
  15856. return this._ranges[name];
  15857. };
  15858. /**
  15859. * Will start the animation sequence
  15860. * @param name defines the range frames for animation sequence
  15861. * @param loop defines if the animation should loop (false by default)
  15862. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15863. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15864. * @returns the object created for this animation. If range does not exist, it will return null
  15865. */
  15866. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15867. var range = this.getAnimationRange(name);
  15868. if (!range) {
  15869. return null;
  15870. }
  15871. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15872. };
  15873. /**
  15874. * Serialize animation ranges into a JSON compatible object
  15875. * @returns serialization object
  15876. */
  15877. Node.prototype.serializeAnimationRanges = function () {
  15878. var serializationRanges = [];
  15879. for (var name in this._ranges) {
  15880. var localRange = this._ranges[name];
  15881. if (!localRange) {
  15882. continue;
  15883. }
  15884. var range = {};
  15885. range.name = name;
  15886. range.from = localRange.from;
  15887. range.to = localRange.to;
  15888. serializationRanges.push(range);
  15889. }
  15890. return serializationRanges;
  15891. };
  15892. /**
  15893. * Computes the world matrix of the node
  15894. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15895. * @returns the world matrix
  15896. */
  15897. Node.prototype.computeWorldMatrix = function (force) {
  15898. return BABYLON.Matrix.Identity();
  15899. };
  15900. /**
  15901. * Releases resources associated with this node.
  15902. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  15903. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  15904. */
  15905. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15906. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15907. if (!doNotRecurse) {
  15908. var nodes = this.getDescendants(true);
  15909. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  15910. var node = nodes_1[_i];
  15911. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  15912. }
  15913. }
  15914. else {
  15915. var transformNodes = this.getChildTransformNodes(true);
  15916. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  15917. var transformNode = transformNodes_1[_a];
  15918. transformNode.parent = null;
  15919. transformNode.computeWorldMatrix(true);
  15920. }
  15921. }
  15922. this.parent = null;
  15923. // Callback
  15924. this.onDisposeObservable.notifyObservers(this);
  15925. this.onDisposeObservable.clear();
  15926. // Behaviors
  15927. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  15928. var behavior = _c[_b];
  15929. behavior.detach();
  15930. }
  15931. this._behaviors = [];
  15932. this._isDisposed = true;
  15933. };
  15934. /**
  15935. * Parse animation range data from a serialization object and store them into a given node
  15936. * @param node defines where to store the animation ranges
  15937. * @param parsedNode defines the serialization object to read data from
  15938. * @param scene defines the hosting scene
  15939. */
  15940. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15941. if (parsedNode.ranges) {
  15942. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15943. var data = parsedNode.ranges[index];
  15944. node.createAnimationRange(data.name, data.from, data.to);
  15945. }
  15946. }
  15947. };
  15948. __decorate([
  15949. BABYLON.serialize()
  15950. ], Node.prototype, "name", void 0);
  15951. __decorate([
  15952. BABYLON.serialize()
  15953. ], Node.prototype, "id", void 0);
  15954. __decorate([
  15955. BABYLON.serialize()
  15956. ], Node.prototype, "uniqueId", void 0);
  15957. __decorate([
  15958. BABYLON.serialize()
  15959. ], Node.prototype, "state", void 0);
  15960. __decorate([
  15961. BABYLON.serialize()
  15962. ], Node.prototype, "metadata", void 0);
  15963. return Node;
  15964. }());
  15965. BABYLON.Node = Node;
  15966. })(BABYLON || (BABYLON = {}));
  15967. //# sourceMappingURL=babylon.node.js.map
  15968. var BABYLON;
  15969. (function (BABYLON) {
  15970. var BoundingSphere = /** @class */ (function () {
  15971. function BoundingSphere(minimum, maximum) {
  15972. this.minimum = minimum;
  15973. this.maximum = maximum;
  15974. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15975. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15976. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15977. this.radius = distance * 0.5;
  15978. this.centerWorld = BABYLON.Vector3.Zero();
  15979. this._update(BABYLON.Matrix.Identity());
  15980. }
  15981. // Methods
  15982. BoundingSphere.prototype._update = function (world) {
  15983. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15984. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15985. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15986. };
  15987. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15988. for (var i = 0; i < 6; i++) {
  15989. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15990. return false;
  15991. }
  15992. return true;
  15993. };
  15994. BoundingSphere.prototype.intersectsPoint = function (point) {
  15995. var x = this.centerWorld.x - point.x;
  15996. var y = this.centerWorld.y - point.y;
  15997. var z = this.centerWorld.z - point.z;
  15998. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15999. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16000. return false;
  16001. return true;
  16002. };
  16003. // Statics
  16004. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16005. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16006. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16007. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16008. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16009. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16010. return false;
  16011. return true;
  16012. };
  16013. return BoundingSphere;
  16014. }());
  16015. BABYLON.BoundingSphere = BoundingSphere;
  16016. })(BABYLON || (BABYLON = {}));
  16017. //# sourceMappingURL=babylon.boundingSphere.js.map
  16018. var BABYLON;
  16019. (function (BABYLON) {
  16020. var BoundingBox = /** @class */ (function () {
  16021. function BoundingBox(minimum, maximum) {
  16022. this.minimum = minimum;
  16023. this.maximum = maximum;
  16024. this.vectors = new Array();
  16025. this.vectorsWorld = new Array();
  16026. // Bounding vectors
  16027. this.vectors.push(this.minimum.clone());
  16028. this.vectors.push(this.maximum.clone());
  16029. this.vectors.push(this.minimum.clone());
  16030. this.vectors[2].x = this.maximum.x;
  16031. this.vectors.push(this.minimum.clone());
  16032. this.vectors[3].y = this.maximum.y;
  16033. this.vectors.push(this.minimum.clone());
  16034. this.vectors[4].z = this.maximum.z;
  16035. this.vectors.push(this.maximum.clone());
  16036. this.vectors[5].z = this.minimum.z;
  16037. this.vectors.push(this.maximum.clone());
  16038. this.vectors[6].x = this.minimum.x;
  16039. this.vectors.push(this.maximum.clone());
  16040. this.vectors[7].y = this.minimum.y;
  16041. // OBB
  16042. this.center = this.maximum.add(this.minimum).scale(0.5);
  16043. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16044. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16045. // World
  16046. for (var index = 0; index < this.vectors.length; index++) {
  16047. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16048. }
  16049. this.minimumWorld = BABYLON.Vector3.Zero();
  16050. this.maximumWorld = BABYLON.Vector3.Zero();
  16051. this.centerWorld = BABYLON.Vector3.Zero();
  16052. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16053. this._update(BABYLON.Matrix.Identity());
  16054. }
  16055. // Methods
  16056. BoundingBox.prototype.getWorldMatrix = function () {
  16057. return this._worldMatrix;
  16058. };
  16059. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16060. this._worldMatrix.copyFrom(matrix);
  16061. return this;
  16062. };
  16063. BoundingBox.prototype._update = function (world) {
  16064. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16065. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16066. for (var index = 0; index < this.vectors.length; index++) {
  16067. var v = this.vectorsWorld[index];
  16068. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16069. if (v.x < this.minimumWorld.x)
  16070. this.minimumWorld.x = v.x;
  16071. if (v.y < this.minimumWorld.y)
  16072. this.minimumWorld.y = v.y;
  16073. if (v.z < this.minimumWorld.z)
  16074. this.minimumWorld.z = v.z;
  16075. if (v.x > this.maximumWorld.x)
  16076. this.maximumWorld.x = v.x;
  16077. if (v.y > this.maximumWorld.y)
  16078. this.maximumWorld.y = v.y;
  16079. if (v.z > this.maximumWorld.z)
  16080. this.maximumWorld.z = v.z;
  16081. }
  16082. // Extend
  16083. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16084. this.extendSizeWorld.scaleInPlace(0.5);
  16085. // OBB
  16086. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16087. this.centerWorld.scaleInPlace(0.5);
  16088. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16089. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16090. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16091. this._worldMatrix = world;
  16092. };
  16093. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16094. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16095. };
  16096. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16097. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16098. };
  16099. BoundingBox.prototype.intersectsPoint = function (point) {
  16100. var delta = -BABYLON.Epsilon;
  16101. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16102. return false;
  16103. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16104. return false;
  16105. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16106. return false;
  16107. return true;
  16108. };
  16109. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16110. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16111. };
  16112. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16113. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16114. return false;
  16115. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16116. return false;
  16117. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16118. return false;
  16119. return true;
  16120. };
  16121. // Statics
  16122. BoundingBox.Intersects = function (box0, box1) {
  16123. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16124. return false;
  16125. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16126. return false;
  16127. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16128. return false;
  16129. return true;
  16130. };
  16131. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16132. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16133. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16134. return (num <= (sphereRadius * sphereRadius));
  16135. };
  16136. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16137. for (var p = 0; p < 6; p++) {
  16138. for (var i = 0; i < 8; i++) {
  16139. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16140. return false;
  16141. }
  16142. }
  16143. }
  16144. return true;
  16145. };
  16146. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16147. for (var p = 0; p < 6; p++) {
  16148. var inCount = 8;
  16149. for (var i = 0; i < 8; i++) {
  16150. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16151. --inCount;
  16152. }
  16153. else {
  16154. break;
  16155. }
  16156. }
  16157. if (inCount === 0)
  16158. return false;
  16159. }
  16160. return true;
  16161. };
  16162. return BoundingBox;
  16163. }());
  16164. BABYLON.BoundingBox = BoundingBox;
  16165. })(BABYLON || (BABYLON = {}));
  16166. //# sourceMappingURL=babylon.boundingBox.js.map
  16167. var BABYLON;
  16168. (function (BABYLON) {
  16169. var computeBoxExtents = function (axis, box) {
  16170. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16171. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16172. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16173. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16174. var r = r0 + r1 + r2;
  16175. return {
  16176. min: p - r,
  16177. max: p + r
  16178. };
  16179. };
  16180. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16181. var axisOverlap = function (axis, box0, box1) {
  16182. var result0 = computeBoxExtents(axis, box0);
  16183. var result1 = computeBoxExtents(axis, box1);
  16184. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16185. };
  16186. var BoundingInfo = /** @class */ (function () {
  16187. function BoundingInfo(minimum, maximum) {
  16188. this.minimum = minimum;
  16189. this.maximum = maximum;
  16190. this._isLocked = false;
  16191. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16192. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16193. }
  16194. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16195. get: function () {
  16196. return this._isLocked;
  16197. },
  16198. set: function (value) {
  16199. this._isLocked = value;
  16200. },
  16201. enumerable: true,
  16202. configurable: true
  16203. });
  16204. // Methods
  16205. BoundingInfo.prototype.update = function (world) {
  16206. if (this._isLocked) {
  16207. return;
  16208. }
  16209. this.boundingBox._update(world);
  16210. this.boundingSphere._update(world);
  16211. };
  16212. /**
  16213. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16214. * @param center New center of the bounding info
  16215. * @param extend New extend of the bounding info
  16216. */
  16217. BoundingInfo.prototype.centerOn = function (center, extend) {
  16218. this.minimum = center.subtract(extend);
  16219. this.maximum = center.add(extend);
  16220. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16221. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16222. return this;
  16223. };
  16224. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16225. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16226. return false;
  16227. return this.boundingBox.isInFrustum(frustumPlanes);
  16228. };
  16229. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16230. /**
  16231. * Gets the world distance between the min and max points of the bounding box
  16232. */
  16233. get: function () {
  16234. var boundingBox = this.boundingBox;
  16235. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16236. return size.length();
  16237. },
  16238. enumerable: true,
  16239. configurable: true
  16240. });
  16241. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16242. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16243. };
  16244. BoundingInfo.prototype._checkCollision = function (collider) {
  16245. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16246. };
  16247. BoundingInfo.prototype.intersectsPoint = function (point) {
  16248. if (!this.boundingSphere.centerWorld) {
  16249. return false;
  16250. }
  16251. if (!this.boundingSphere.intersectsPoint(point)) {
  16252. return false;
  16253. }
  16254. if (!this.boundingBox.intersectsPoint(point)) {
  16255. return false;
  16256. }
  16257. return true;
  16258. };
  16259. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16260. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16261. return false;
  16262. }
  16263. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16264. return false;
  16265. }
  16266. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16267. return false;
  16268. }
  16269. if (!precise) {
  16270. return true;
  16271. }
  16272. var box0 = this.boundingBox;
  16273. var box1 = boundingInfo.boundingBox;
  16274. if (!axisOverlap(box0.directions[0], box0, box1))
  16275. return false;
  16276. if (!axisOverlap(box0.directions[1], box0, box1))
  16277. return false;
  16278. if (!axisOverlap(box0.directions[2], box0, box1))
  16279. return false;
  16280. if (!axisOverlap(box1.directions[0], box0, box1))
  16281. return false;
  16282. if (!axisOverlap(box1.directions[1], box0, box1))
  16283. return false;
  16284. if (!axisOverlap(box1.directions[2], box0, box1))
  16285. return false;
  16286. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16287. return false;
  16288. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16289. return false;
  16290. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16291. return false;
  16292. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16293. return false;
  16294. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16295. return false;
  16296. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16297. return false;
  16298. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16299. return false;
  16300. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16301. return false;
  16302. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16303. return false;
  16304. return true;
  16305. };
  16306. return BoundingInfo;
  16307. }());
  16308. BABYLON.BoundingInfo = BoundingInfo;
  16309. })(BABYLON || (BABYLON = {}));
  16310. //# sourceMappingURL=babylon.boundingInfo.js.map
  16311. var BABYLON;
  16312. (function (BABYLON) {
  16313. var TransformNode = /** @class */ (function (_super) {
  16314. __extends(TransformNode, _super);
  16315. function TransformNode(name, scene, isPure) {
  16316. if (scene === void 0) { scene = null; }
  16317. if (isPure === void 0) { isPure = true; }
  16318. var _this = _super.call(this, name, scene) || this;
  16319. // Properties
  16320. _this._rotation = BABYLON.Vector3.Zero();
  16321. _this._scaling = BABYLON.Vector3.One();
  16322. _this._isDirty = false;
  16323. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16324. _this.scalingDeterminant = 1;
  16325. _this.infiniteDistance = false;
  16326. _this.position = BABYLON.Vector3.Zero();
  16327. _this._localWorld = BABYLON.Matrix.Zero();
  16328. _this._worldMatrix = BABYLON.Matrix.Zero();
  16329. _this._worldMatrixDeterminant = 0;
  16330. _this._absolutePosition = BABYLON.Vector3.Zero();
  16331. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16332. _this._postMultiplyPivotMatrix = false;
  16333. _this._isWorldMatrixFrozen = false;
  16334. /**
  16335. * An event triggered after the world matrix is updated
  16336. * @type {BABYLON.Observable}
  16337. */
  16338. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16339. _this._nonUniformScaling = false;
  16340. if (isPure) {
  16341. _this.getScene().addTransformNode(_this);
  16342. }
  16343. return _this;
  16344. }
  16345. /**
  16346. * Gets a string idenfifying the name of the class
  16347. * @returns "TransformNode" string
  16348. */
  16349. TransformNode.prototype.getClassName = function () {
  16350. return "TransformNode";
  16351. };
  16352. Object.defineProperty(TransformNode.prototype, "rotation", {
  16353. /**
  16354. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16355. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16356. * Default : (0.0, 0.0, 0.0)
  16357. */
  16358. get: function () {
  16359. return this._rotation;
  16360. },
  16361. set: function (newRotation) {
  16362. this._rotation = newRotation;
  16363. },
  16364. enumerable: true,
  16365. configurable: true
  16366. });
  16367. Object.defineProperty(TransformNode.prototype, "scaling", {
  16368. /**
  16369. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16370. * Default : (1.0, 1.0, 1.0)
  16371. */
  16372. get: function () {
  16373. return this._scaling;
  16374. },
  16375. /**
  16376. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16377. * Default : (1.0, 1.0, 1.0)
  16378. */
  16379. set: function (newScaling) {
  16380. this._scaling = newScaling;
  16381. },
  16382. enumerable: true,
  16383. configurable: true
  16384. });
  16385. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16386. /**
  16387. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16388. * It's null by default.
  16389. * 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)
  16390. */
  16391. get: function () {
  16392. return this._rotationQuaternion;
  16393. },
  16394. set: function (quaternion) {
  16395. this._rotationQuaternion = quaternion;
  16396. //reset the rotation vector.
  16397. if (quaternion && this.rotation.length()) {
  16398. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16399. }
  16400. },
  16401. enumerable: true,
  16402. configurable: true
  16403. });
  16404. /**
  16405. * Returns the latest update of the World matrix
  16406. * Returns a Matrix.
  16407. */
  16408. TransformNode.prototype.getWorldMatrix = function () {
  16409. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16410. this.computeWorldMatrix();
  16411. }
  16412. return this._worldMatrix;
  16413. };
  16414. /**
  16415. * Returns the latest update of the World matrix determinant.
  16416. */
  16417. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16418. return this._worldMatrixDeterminant;
  16419. };
  16420. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16421. /**
  16422. * Returns directly the latest state of the mesh World matrix.
  16423. * A Matrix is returned.
  16424. */
  16425. get: function () {
  16426. return this._worldMatrix;
  16427. },
  16428. enumerable: true,
  16429. configurable: true
  16430. });
  16431. /**
  16432. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16433. * Returns the AbstractMesh.
  16434. */
  16435. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16436. this._poseMatrix.copyFrom(matrix);
  16437. return this;
  16438. };
  16439. /**
  16440. * Returns the mesh Pose matrix.
  16441. * Returned object : Matrix
  16442. */
  16443. TransformNode.prototype.getPoseMatrix = function () {
  16444. return this._poseMatrix;
  16445. };
  16446. TransformNode.prototype._isSynchronized = function () {
  16447. if (this._isDirty) {
  16448. return false;
  16449. }
  16450. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16451. return false;
  16452. if (this._cache.pivotMatrixUpdated) {
  16453. return false;
  16454. }
  16455. if (this.infiniteDistance) {
  16456. return false;
  16457. }
  16458. if (!this._cache.position.equals(this.position))
  16459. return false;
  16460. if (this.rotationQuaternion) {
  16461. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16462. return false;
  16463. }
  16464. if (!this._cache.rotation.equals(this.rotation))
  16465. return false;
  16466. if (!this._cache.scaling.equals(this.scaling))
  16467. return false;
  16468. return true;
  16469. };
  16470. TransformNode.prototype._initCache = function () {
  16471. _super.prototype._initCache.call(this);
  16472. this._cache.localMatrixUpdated = false;
  16473. this._cache.position = BABYLON.Vector3.Zero();
  16474. this._cache.scaling = BABYLON.Vector3.Zero();
  16475. this._cache.rotation = BABYLON.Vector3.Zero();
  16476. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16477. this._cache.billboardMode = -1;
  16478. };
  16479. TransformNode.prototype.markAsDirty = function (property) {
  16480. if (property === "rotation") {
  16481. this.rotationQuaternion = null;
  16482. }
  16483. this._currentRenderId = Number.MAX_VALUE;
  16484. this._isDirty = true;
  16485. return this;
  16486. };
  16487. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16488. /**
  16489. * Returns the current mesh absolute position.
  16490. * Retuns a Vector3.
  16491. */
  16492. get: function () {
  16493. return this._absolutePosition;
  16494. },
  16495. enumerable: true,
  16496. configurable: true
  16497. });
  16498. /**
  16499. * Sets a new matrix to apply before all other transformation
  16500. * @param matrix defines the transform matrix
  16501. * @returns the current TransformNode
  16502. */
  16503. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16504. return this.setPivotMatrix(matrix, false);
  16505. };
  16506. /**
  16507. * Sets a new pivot matrix to the current node
  16508. * @param matrix defines the new pivot matrix to use
  16509. * @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
  16510. * @returns the current TransformNode
  16511. */
  16512. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16513. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16514. this._pivotMatrix = matrix.clone();
  16515. this._cache.pivotMatrixUpdated = true;
  16516. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16517. if (this._postMultiplyPivotMatrix) {
  16518. if (!this._pivotMatrixInverse) {
  16519. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16520. }
  16521. else {
  16522. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16523. }
  16524. }
  16525. return this;
  16526. };
  16527. /**
  16528. * Returns the mesh pivot matrix.
  16529. * Default : Identity.
  16530. * A Matrix is returned.
  16531. */
  16532. TransformNode.prototype.getPivotMatrix = function () {
  16533. return this._pivotMatrix;
  16534. };
  16535. /**
  16536. * Prevents the World matrix to be computed any longer.
  16537. * Returns the AbstractMesh.
  16538. */
  16539. TransformNode.prototype.freezeWorldMatrix = function () {
  16540. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16541. this.computeWorldMatrix(true);
  16542. this._isWorldMatrixFrozen = true;
  16543. return this;
  16544. };
  16545. /**
  16546. * Allows back the World matrix computation.
  16547. * Returns the AbstractMesh.
  16548. */
  16549. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16550. this._isWorldMatrixFrozen = false;
  16551. this.computeWorldMatrix(true);
  16552. return this;
  16553. };
  16554. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16555. /**
  16556. * True if the World matrix has been frozen.
  16557. * Returns a boolean.
  16558. */
  16559. get: function () {
  16560. return this._isWorldMatrixFrozen;
  16561. },
  16562. enumerable: true,
  16563. configurable: true
  16564. });
  16565. /**
  16566. * Retuns the mesh absolute position in the World.
  16567. * Returns a Vector3.
  16568. */
  16569. TransformNode.prototype.getAbsolutePosition = function () {
  16570. this.computeWorldMatrix();
  16571. return this._absolutePosition;
  16572. };
  16573. /**
  16574. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16575. * Returns the AbstractMesh.
  16576. */
  16577. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16578. if (!absolutePosition) {
  16579. return this;
  16580. }
  16581. var absolutePositionX;
  16582. var absolutePositionY;
  16583. var absolutePositionZ;
  16584. if (absolutePosition.x === undefined) {
  16585. if (arguments.length < 3) {
  16586. return this;
  16587. }
  16588. absolutePositionX = arguments[0];
  16589. absolutePositionY = arguments[1];
  16590. absolutePositionZ = arguments[2];
  16591. }
  16592. else {
  16593. absolutePositionX = absolutePosition.x;
  16594. absolutePositionY = absolutePosition.y;
  16595. absolutePositionZ = absolutePosition.z;
  16596. }
  16597. if (this.parent) {
  16598. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16599. invertParentWorldMatrix.invert();
  16600. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16601. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16602. }
  16603. else {
  16604. this.position.x = absolutePositionX;
  16605. this.position.y = absolutePositionY;
  16606. this.position.z = absolutePositionZ;
  16607. }
  16608. return this;
  16609. };
  16610. /**
  16611. * Sets the mesh position in its local space.
  16612. * Returns the AbstractMesh.
  16613. */
  16614. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16615. this.computeWorldMatrix();
  16616. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16617. return this;
  16618. };
  16619. /**
  16620. * Returns the mesh position in the local space from the current World matrix values.
  16621. * Returns a new Vector3.
  16622. */
  16623. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16624. this.computeWorldMatrix();
  16625. var invLocalWorldMatrix = this._localWorld.clone();
  16626. invLocalWorldMatrix.invert();
  16627. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16628. };
  16629. /**
  16630. * Translates the mesh along the passed Vector3 in its local space.
  16631. * Returns the AbstractMesh.
  16632. */
  16633. TransformNode.prototype.locallyTranslate = function (vector3) {
  16634. this.computeWorldMatrix(true);
  16635. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16636. return this;
  16637. };
  16638. /**
  16639. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16640. * @param targetPoint the position (must be in same space as current mesh) to look at
  16641. * @param yawCor optional yaw (y-axis) correction in radians
  16642. * @param pitchCor optional pitch (x-axis) correction in radians
  16643. * @param rollCor optional roll (z-axis) correction in radians
  16644. * @param space the choosen space of the target
  16645. * @returns the TransformNode.
  16646. */
  16647. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16648. if (yawCor === void 0) { yawCor = 0; }
  16649. if (pitchCor === void 0) { pitchCor = 0; }
  16650. if (rollCor === void 0) { rollCor = 0; }
  16651. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16652. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16653. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16654. targetPoint.subtractToRef(pos, dv);
  16655. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16656. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16657. var pitch = Math.atan2(dv.y, len);
  16658. if (this.rotationQuaternion) {
  16659. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16660. }
  16661. else {
  16662. this.rotation.x = pitch + pitchCor;
  16663. this.rotation.y = yaw + yawCor;
  16664. this.rotation.z = rollCor;
  16665. }
  16666. return this;
  16667. };
  16668. /**
  16669. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16670. * This Vector3 is expressed in the World space.
  16671. */
  16672. TransformNode.prototype.getDirection = function (localAxis) {
  16673. var result = BABYLON.Vector3.Zero();
  16674. this.getDirectionToRef(localAxis, result);
  16675. return result;
  16676. };
  16677. /**
  16678. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16679. * localAxis is expressed in the mesh local space.
  16680. * result is computed in the Wordl space from the mesh World matrix.
  16681. * Returns the AbstractMesh.
  16682. */
  16683. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16684. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16685. return this;
  16686. };
  16687. /**
  16688. * Sets a new pivot point to the current node
  16689. * @param point defines the new pivot point to use
  16690. * @param space defines if the point is in world or local space (local by default)
  16691. * @returns the current TransformNode
  16692. */
  16693. TransformNode.prototype.setPivotPoint = function (point, space) {
  16694. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16695. if (this.getScene().getRenderId() == 0) {
  16696. this.computeWorldMatrix(true);
  16697. }
  16698. var wm = this.getWorldMatrix();
  16699. if (space == BABYLON.Space.WORLD) {
  16700. var tmat = BABYLON.Tmp.Matrix[0];
  16701. wm.invertToRef(tmat);
  16702. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16703. }
  16704. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16705. };
  16706. /**
  16707. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16708. */
  16709. TransformNode.prototype.getPivotPoint = function () {
  16710. var point = BABYLON.Vector3.Zero();
  16711. this.getPivotPointToRef(point);
  16712. return point;
  16713. };
  16714. /**
  16715. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16716. * Returns the AbstractMesh.
  16717. */
  16718. TransformNode.prototype.getPivotPointToRef = function (result) {
  16719. result.x = -this._pivotMatrix.m[12];
  16720. result.y = -this._pivotMatrix.m[13];
  16721. result.z = -this._pivotMatrix.m[14];
  16722. return this;
  16723. };
  16724. /**
  16725. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16726. */
  16727. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16728. var point = BABYLON.Vector3.Zero();
  16729. this.getAbsolutePivotPointToRef(point);
  16730. return point;
  16731. };
  16732. /**
  16733. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16734. * Returns the AbstractMesh.
  16735. */
  16736. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16737. result.x = this._pivotMatrix.m[12];
  16738. result.y = this._pivotMatrix.m[13];
  16739. result.z = this._pivotMatrix.m[14];
  16740. this.getPivotPointToRef(result);
  16741. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16742. return this;
  16743. };
  16744. /**
  16745. * Defines the passed node as the parent of the current node.
  16746. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16747. * Returns the TransformNode.
  16748. */
  16749. TransformNode.prototype.setParent = function (node) {
  16750. if (node === null) {
  16751. var rotation = BABYLON.Tmp.Quaternion[0];
  16752. var position = BABYLON.Tmp.Vector3[0];
  16753. var scale = BABYLON.Tmp.Vector3[1];
  16754. if (this.parent && this.parent.computeWorldMatrix) {
  16755. this.parent.computeWorldMatrix(true);
  16756. }
  16757. this.computeWorldMatrix(true);
  16758. this.getWorldMatrix().decompose(scale, rotation, position);
  16759. if (this.rotationQuaternion) {
  16760. this.rotationQuaternion.copyFrom(rotation);
  16761. }
  16762. else {
  16763. rotation.toEulerAnglesToRef(this.rotation);
  16764. }
  16765. this.scaling.x = scale.x;
  16766. this.scaling.y = scale.y;
  16767. this.scaling.z = scale.z;
  16768. this.position.x = position.x;
  16769. this.position.y = position.y;
  16770. this.position.z = position.z;
  16771. }
  16772. else {
  16773. var rotation = BABYLON.Tmp.Quaternion[0];
  16774. var position = BABYLON.Tmp.Vector3[0];
  16775. var scale = BABYLON.Tmp.Vector3[1];
  16776. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16777. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16778. this.computeWorldMatrix(true);
  16779. node.computeWorldMatrix(true);
  16780. node.getWorldMatrix().invertToRef(invParentMatrix);
  16781. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16782. diffMatrix.decompose(scale, rotation, position);
  16783. if (this.rotationQuaternion) {
  16784. this.rotationQuaternion.copyFrom(rotation);
  16785. }
  16786. else {
  16787. rotation.toEulerAnglesToRef(this.rotation);
  16788. }
  16789. this.position.x = position.x;
  16790. this.position.y = position.y;
  16791. this.position.z = position.z;
  16792. this.scaling.x = scale.x;
  16793. this.scaling.y = scale.y;
  16794. this.scaling.z = scale.z;
  16795. }
  16796. this.parent = node;
  16797. return this;
  16798. };
  16799. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16800. get: function () {
  16801. return this._nonUniformScaling;
  16802. },
  16803. enumerable: true,
  16804. configurable: true
  16805. });
  16806. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16807. if (this._nonUniformScaling === value) {
  16808. return false;
  16809. }
  16810. this._nonUniformScaling = true;
  16811. return true;
  16812. };
  16813. /**
  16814. * Attach the current TransformNode to another TransformNode associated with a bone
  16815. * @param bone Bone affecting the TransformNode
  16816. * @param affectedTransformNode TransformNode associated with the bone
  16817. */
  16818. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16819. this._transformToBoneReferal = affectedTransformNode;
  16820. this.parent = bone;
  16821. if (bone.getWorldMatrix().determinant() < 0) {
  16822. this.scalingDeterminant *= -1;
  16823. }
  16824. return this;
  16825. };
  16826. TransformNode.prototype.detachFromBone = function () {
  16827. if (!this.parent) {
  16828. return this;
  16829. }
  16830. if (this.parent.getWorldMatrix().determinant() < 0) {
  16831. this.scalingDeterminant *= -1;
  16832. }
  16833. this._transformToBoneReferal = null;
  16834. this.parent = null;
  16835. return this;
  16836. };
  16837. /**
  16838. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16839. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16840. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16841. * The passed axis is also normalized.
  16842. * Returns the AbstractMesh.
  16843. */
  16844. TransformNode.prototype.rotate = function (axis, amount, space) {
  16845. axis.normalize();
  16846. if (!this.rotationQuaternion) {
  16847. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16848. this.rotation = BABYLON.Vector3.Zero();
  16849. }
  16850. var rotationQuaternion;
  16851. if (!space || space === BABYLON.Space.LOCAL) {
  16852. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16853. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16854. }
  16855. else {
  16856. if (this.parent) {
  16857. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16858. invertParentWorldMatrix.invert();
  16859. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16860. }
  16861. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16862. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16863. }
  16864. return this;
  16865. };
  16866. /**
  16867. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16868. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16869. * The passed axis is also normalized.
  16870. * Returns the AbstractMesh.
  16871. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16872. */
  16873. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16874. axis.normalize();
  16875. if (!this.rotationQuaternion) {
  16876. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16877. this.rotation.copyFromFloats(0, 0, 0);
  16878. }
  16879. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16880. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16881. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16882. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16883. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16884. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16885. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16886. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16887. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16888. return this;
  16889. };
  16890. /**
  16891. * Translates the mesh along the axis vector for the passed distance in the given space.
  16892. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16893. * Returns the AbstractMesh.
  16894. */
  16895. TransformNode.prototype.translate = function (axis, distance, space) {
  16896. var displacementVector = axis.scale(distance);
  16897. if (!space || space === BABYLON.Space.LOCAL) {
  16898. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16899. this.setPositionWithLocalVector(tempV3);
  16900. }
  16901. else {
  16902. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16903. }
  16904. return this;
  16905. };
  16906. /**
  16907. * Adds a rotation step to the mesh current rotation.
  16908. * x, y, z are Euler angles expressed in radians.
  16909. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16910. * This means this rotation is made in the mesh local space only.
  16911. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16912. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16913. * ```javascript
  16914. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16915. * ```
  16916. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16917. * 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.
  16918. * Returns the AbstractMesh.
  16919. */
  16920. TransformNode.prototype.addRotation = function (x, y, z) {
  16921. var rotationQuaternion;
  16922. if (this.rotationQuaternion) {
  16923. rotationQuaternion = this.rotationQuaternion;
  16924. }
  16925. else {
  16926. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16927. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16928. }
  16929. var accumulation = BABYLON.Tmp.Quaternion[0];
  16930. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16931. rotationQuaternion.multiplyInPlace(accumulation);
  16932. if (!this.rotationQuaternion) {
  16933. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16934. }
  16935. return this;
  16936. };
  16937. /**
  16938. * Computes the mesh World matrix and returns it.
  16939. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16940. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16941. * If the parameter `force`is set to `true`, the actual computation is done.
  16942. * Returns the mesh World Matrix.
  16943. */
  16944. TransformNode.prototype.computeWorldMatrix = function (force) {
  16945. if (this._isWorldMatrixFrozen) {
  16946. return this._worldMatrix;
  16947. }
  16948. if (!force && this.isSynchronized(true)) {
  16949. return this._worldMatrix;
  16950. }
  16951. this._cache.position.copyFrom(this.position);
  16952. this._cache.scaling.copyFrom(this.scaling);
  16953. this._cache.pivotMatrixUpdated = false;
  16954. this._cache.billboardMode = this.billboardMode;
  16955. this._currentRenderId = this.getScene().getRenderId();
  16956. this._isDirty = false;
  16957. // Scaling
  16958. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16959. // Rotation
  16960. //rotate, if quaternion is set and rotation was used
  16961. if (this.rotationQuaternion) {
  16962. var len = this.rotation.length();
  16963. if (len) {
  16964. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16965. this.rotation.copyFromFloats(0, 0, 0);
  16966. }
  16967. }
  16968. if (this.rotationQuaternion) {
  16969. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16970. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16971. }
  16972. else {
  16973. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16974. this._cache.rotation.copyFrom(this.rotation);
  16975. }
  16976. // Translation
  16977. var camera = this.getScene().activeCamera;
  16978. if (this.infiniteDistance && !this.parent && camera) {
  16979. var cameraWorldMatrix = camera.getWorldMatrix();
  16980. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16981. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16982. }
  16983. else {
  16984. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16985. }
  16986. // Composing transformations
  16987. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16988. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16989. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16990. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16991. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16992. // Need to decompose each rotation here
  16993. var currentPosition = BABYLON.Tmp.Vector3[3];
  16994. if (this.parent && this.parent.getWorldMatrix) {
  16995. if (this._transformToBoneReferal) {
  16996. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16997. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16998. }
  16999. else {
  17000. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17001. }
  17002. }
  17003. else {
  17004. currentPosition.copyFrom(this.position);
  17005. }
  17006. currentPosition.subtractInPlace(camera.globalPosition);
  17007. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17008. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17009. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17010. }
  17011. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17012. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17013. }
  17014. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17015. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17016. }
  17017. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17018. }
  17019. else {
  17020. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17021. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17022. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17023. }
  17024. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17025. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17026. }
  17027. // Local world
  17028. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17029. // Parent
  17030. if (this.parent && this.parent.getWorldMatrix) {
  17031. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17032. if (this._transformToBoneReferal) {
  17033. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17034. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17035. }
  17036. else {
  17037. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17038. }
  17039. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17040. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17041. this._worldMatrix.copyFrom(this._localWorld);
  17042. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17043. }
  17044. else {
  17045. if (this._transformToBoneReferal) {
  17046. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17047. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17048. }
  17049. else {
  17050. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17051. }
  17052. }
  17053. this._markSyncedWithParent();
  17054. }
  17055. else {
  17056. this._worldMatrix.copyFrom(this._localWorld);
  17057. }
  17058. // Post multiply inverse of pivotMatrix
  17059. if (this._postMultiplyPivotMatrix) {
  17060. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17061. }
  17062. // Normal matrix
  17063. if (this.scaling.isNonUniform) {
  17064. this._updateNonUniformScalingState(true);
  17065. }
  17066. else if (this.parent && this.parent._nonUniformScaling) {
  17067. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17068. }
  17069. else {
  17070. this._updateNonUniformScalingState(false);
  17071. }
  17072. this._afterComputeWorldMatrix();
  17073. // Absolute position
  17074. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17075. // Callbacks
  17076. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17077. if (!this._poseMatrix) {
  17078. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17079. }
  17080. // Cache the determinant
  17081. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17082. return this._worldMatrix;
  17083. };
  17084. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17085. };
  17086. /**
  17087. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17088. * @param func: callback function to add
  17089. *
  17090. * Returns the TransformNode.
  17091. */
  17092. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17093. this.onAfterWorldMatrixUpdateObservable.add(func);
  17094. return this;
  17095. };
  17096. /**
  17097. * Removes a registered callback function.
  17098. * Returns the TransformNode.
  17099. */
  17100. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17101. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17102. return this;
  17103. };
  17104. /**
  17105. * Clone the current transform node
  17106. * Returns the new transform node
  17107. * @param name Name of the new clone
  17108. * @param newParent New parent for the clone
  17109. * @param doNotCloneChildren Do not clone children hierarchy
  17110. */
  17111. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17112. var _this = this;
  17113. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17114. result.name = name;
  17115. result.id = name;
  17116. if (newParent) {
  17117. result.parent = newParent;
  17118. }
  17119. if (!doNotCloneChildren) {
  17120. // Children
  17121. var directDescendants = this.getDescendants(true);
  17122. for (var index = 0; index < directDescendants.length; index++) {
  17123. var child = directDescendants[index];
  17124. if (child.clone) {
  17125. child.clone(name + "." + child.name, result);
  17126. }
  17127. }
  17128. }
  17129. return result;
  17130. };
  17131. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17132. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17133. serializationObject.type = this.getClassName();
  17134. // Parent
  17135. if (this.parent) {
  17136. serializationObject.parentId = this.parent.id;
  17137. }
  17138. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17139. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17140. }
  17141. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17142. serializationObject.isEnabled = this.isEnabled();
  17143. // Parent
  17144. if (this.parent) {
  17145. serializationObject.parentId = this.parent.id;
  17146. }
  17147. return serializationObject;
  17148. };
  17149. // Statics
  17150. /**
  17151. * Returns a new TransformNode object parsed from the source provided.
  17152. * The parameter `parsedMesh` is the source.
  17153. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17154. */
  17155. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17156. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17157. if (BABYLON.Tags) {
  17158. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17159. }
  17160. if (parsedTransformNode.localMatrix) {
  17161. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17162. }
  17163. else if (parsedTransformNode.pivotMatrix) {
  17164. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17165. }
  17166. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17167. // Parent
  17168. if (parsedTransformNode.parentId) {
  17169. transformNode._waitingParentId = parsedTransformNode.parentId;
  17170. }
  17171. return transformNode;
  17172. };
  17173. /**
  17174. * Releases resources associated with this transform node.
  17175. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17176. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17177. */
  17178. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17179. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17180. // Animations
  17181. this.getScene().stopAnimation(this);
  17182. // Remove from scene
  17183. this.getScene().removeTransformNode(this);
  17184. this.onAfterWorldMatrixUpdateObservable.clear();
  17185. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17186. };
  17187. // Statics
  17188. TransformNode.BILLBOARDMODE_NONE = 0;
  17189. TransformNode.BILLBOARDMODE_X = 1;
  17190. TransformNode.BILLBOARDMODE_Y = 2;
  17191. TransformNode.BILLBOARDMODE_Z = 4;
  17192. TransformNode.BILLBOARDMODE_ALL = 7;
  17193. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17194. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17195. __decorate([
  17196. BABYLON.serializeAsVector3()
  17197. ], TransformNode.prototype, "_rotation", void 0);
  17198. __decorate([
  17199. BABYLON.serializeAsQuaternion()
  17200. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17201. __decorate([
  17202. BABYLON.serializeAsVector3()
  17203. ], TransformNode.prototype, "_scaling", void 0);
  17204. __decorate([
  17205. BABYLON.serialize()
  17206. ], TransformNode.prototype, "billboardMode", void 0);
  17207. __decorate([
  17208. BABYLON.serialize()
  17209. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17210. __decorate([
  17211. BABYLON.serialize()
  17212. ], TransformNode.prototype, "infiniteDistance", void 0);
  17213. __decorate([
  17214. BABYLON.serializeAsVector3()
  17215. ], TransformNode.prototype, "position", void 0);
  17216. return TransformNode;
  17217. }(BABYLON.Node));
  17218. BABYLON.TransformNode = TransformNode;
  17219. })(BABYLON || (BABYLON = {}));
  17220. //# sourceMappingURL=babylon.transformNode.js.map
  17221. var BABYLON;
  17222. (function (BABYLON) {
  17223. var AbstractMesh = /** @class */ (function (_super) {
  17224. __extends(AbstractMesh, _super);
  17225. // Constructor
  17226. function AbstractMesh(name, scene) {
  17227. if (scene === void 0) { scene = null; }
  17228. var _this = _super.call(this, name, scene, false) || this;
  17229. _this._facetNb = 0; // facet number
  17230. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17231. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17232. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17233. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17234. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17235. _this._subDiv = {
  17236. max: 1,
  17237. X: 1,
  17238. Y: 1,
  17239. Z: 1
  17240. };
  17241. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17242. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17243. // Events
  17244. /**
  17245. * An event triggered when this mesh collides with another one
  17246. * @type {BABYLON.Observable}
  17247. */
  17248. _this.onCollideObservable = new BABYLON.Observable();
  17249. /**
  17250. * An event triggered when the collision's position changes
  17251. * @type {BABYLON.Observable}
  17252. */
  17253. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17254. /**
  17255. * An event triggered when material is changed
  17256. * @type {BABYLON.Observable}
  17257. */
  17258. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17259. // Properties
  17260. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17261. /**
  17262. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17263. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17264. * or
  17265. * 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.
  17266. * for more info check WebGl documentations
  17267. */
  17268. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17269. /**
  17270. * 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:
  17271. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17272. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17273. * 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.
  17274. */
  17275. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17276. /**
  17277. * 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.
  17278. * The default value is -1 which means don't break the query and wait till the result.
  17279. */
  17280. _this.occlusionRetryCount = -1;
  17281. _this._occlusionInternalRetryCounter = 0;
  17282. _this._isOccluded = false;
  17283. _this._isOcclusionQueryInProgress = false;
  17284. _this._visibility = 1.0;
  17285. _this.alphaIndex = Number.MAX_VALUE;
  17286. _this.isVisible = true;
  17287. _this.isPickable = true;
  17288. _this.showBoundingBox = false;
  17289. _this.showSubMeshesBoundingBox = false;
  17290. _this.isBlocker = false;
  17291. _this.enablePointerMoveEvents = false;
  17292. _this.renderingGroupId = 0;
  17293. _this._receiveShadows = false;
  17294. _this.renderOutline = false;
  17295. _this.outlineColor = BABYLON.Color3.Red();
  17296. _this.outlineWidth = 0.02;
  17297. _this.renderOverlay = false;
  17298. _this.overlayColor = BABYLON.Color3.Red();
  17299. _this.overlayAlpha = 0.5;
  17300. _this._hasVertexAlpha = false;
  17301. _this._useVertexColors = true;
  17302. _this._computeBonesUsingShaders = true;
  17303. _this._numBoneInfluencers = 4;
  17304. _this._applyFog = true;
  17305. _this.useOctreeForRenderingSelection = true;
  17306. _this.useOctreeForPicking = true;
  17307. _this.useOctreeForCollisions = true;
  17308. _this._layerMask = 0x0FFFFFFF;
  17309. /**
  17310. * True if the mesh must be rendered in any case.
  17311. */
  17312. _this.alwaysSelectAsActiveMesh = false;
  17313. /**
  17314. * This scene's action manager
  17315. * @type {BABYLON.ActionManager}
  17316. */
  17317. _this.actionManager = null;
  17318. // Physics
  17319. _this.physicsImpostor = null;
  17320. // Collisions
  17321. _this._checkCollisions = false;
  17322. _this._collisionMask = -1;
  17323. _this._collisionGroup = -1;
  17324. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17325. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17326. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17327. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17328. // Edges
  17329. _this.edgesWidth = 1;
  17330. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17331. // Cache
  17332. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17333. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17334. _this._renderId = 0;
  17335. _this._intersectionsInProgress = new Array();
  17336. _this._unIndexed = false;
  17337. _this._lightSources = new Array();
  17338. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17339. if (collidedMesh === void 0) { collidedMesh = null; }
  17340. //TODO move this to the collision coordinator!
  17341. if (_this.getScene().workerCollisions)
  17342. newPosition.multiplyInPlace(_this._collider._radius);
  17343. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17344. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17345. _this.position.addInPlace(_this._diffPositionForCollisions);
  17346. }
  17347. if (collidedMesh) {
  17348. _this.onCollideObservable.notifyObservers(collidedMesh);
  17349. }
  17350. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17351. };
  17352. _this.getScene().addMesh(_this);
  17353. _this._resyncLightSources();
  17354. return _this;
  17355. }
  17356. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17357. get: function () {
  17358. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17359. },
  17360. enumerable: true,
  17361. configurable: true
  17362. });
  17363. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17364. get: function () {
  17365. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17366. },
  17367. enumerable: true,
  17368. configurable: true
  17369. });
  17370. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17371. get: function () {
  17372. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17373. },
  17374. enumerable: true,
  17375. configurable: true
  17376. });
  17377. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17378. get: function () {
  17379. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17380. },
  17381. enumerable: true,
  17382. configurable: true
  17383. });
  17384. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17385. get: function () {
  17386. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17387. },
  17388. enumerable: true,
  17389. configurable: true
  17390. });
  17391. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17392. /**
  17393. * Read-only : the number of facets in the mesh
  17394. */
  17395. get: function () {
  17396. return this._facetNb;
  17397. },
  17398. enumerable: true,
  17399. configurable: true
  17400. });
  17401. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17402. /**
  17403. * The number (integer) of subdivisions per axis in the partioning space
  17404. */
  17405. get: function () {
  17406. return this._partitioningSubdivisions;
  17407. },
  17408. set: function (nb) {
  17409. this._partitioningSubdivisions = nb;
  17410. },
  17411. enumerable: true,
  17412. configurable: true
  17413. });
  17414. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17415. /**
  17416. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17417. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17418. */
  17419. get: function () {
  17420. return this._partitioningBBoxRatio;
  17421. },
  17422. set: function (ratio) {
  17423. this._partitioningBBoxRatio = ratio;
  17424. },
  17425. enumerable: true,
  17426. configurable: true
  17427. });
  17428. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17429. /**
  17430. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17431. * Works only for updatable meshes.
  17432. * Doesn't work with multi-materials.
  17433. */
  17434. get: function () {
  17435. return this._facetDepthSort;
  17436. },
  17437. set: function (sort) {
  17438. this._facetDepthSort = sort;
  17439. },
  17440. enumerable: true,
  17441. configurable: true
  17442. });
  17443. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17444. /**
  17445. * The location (Vector3) where the facet depth sort must be computed from.
  17446. * By default, the active camera position.
  17447. * Used only when facet depth sort is enabled.
  17448. */
  17449. get: function () {
  17450. return this._facetDepthSortFrom;
  17451. },
  17452. set: function (location) {
  17453. this._facetDepthSortFrom = location;
  17454. },
  17455. enumerable: true,
  17456. configurable: true
  17457. });
  17458. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17459. /**
  17460. * Read-only boolean : is the feature facetData enabled ?
  17461. */
  17462. get: function () {
  17463. return this._facetDataEnabled;
  17464. },
  17465. enumerable: true,
  17466. configurable: true
  17467. });
  17468. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17469. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17470. return false;
  17471. }
  17472. this._markSubMeshesAsMiscDirty();
  17473. return true;
  17474. };
  17475. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17476. set: function (callback) {
  17477. if (this._onCollideObserver) {
  17478. this.onCollideObservable.remove(this._onCollideObserver);
  17479. }
  17480. this._onCollideObserver = this.onCollideObservable.add(callback);
  17481. },
  17482. enumerable: true,
  17483. configurable: true
  17484. });
  17485. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17486. set: function (callback) {
  17487. if (this._onCollisionPositionChangeObserver) {
  17488. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17489. }
  17490. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17491. },
  17492. enumerable: true,
  17493. configurable: true
  17494. });
  17495. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17496. /**
  17497. * 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.
  17498. */
  17499. get: function () {
  17500. return this._isOccluded;
  17501. },
  17502. set: function (value) {
  17503. this._isOccluded = value;
  17504. },
  17505. enumerable: true,
  17506. configurable: true
  17507. });
  17508. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17509. /**
  17510. * Flag to check the progress status of the query
  17511. */
  17512. get: function () {
  17513. return this._isOcclusionQueryInProgress;
  17514. },
  17515. enumerable: true,
  17516. configurable: true
  17517. });
  17518. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17519. /**
  17520. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17521. */
  17522. get: function () {
  17523. return this._visibility;
  17524. },
  17525. /**
  17526. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17527. */
  17528. set: function (value) {
  17529. if (this._visibility === value) {
  17530. return;
  17531. }
  17532. this._visibility = value;
  17533. this._markSubMeshesAsMiscDirty();
  17534. },
  17535. enumerable: true,
  17536. configurable: true
  17537. });
  17538. Object.defineProperty(AbstractMesh.prototype, "material", {
  17539. get: function () {
  17540. return this._material;
  17541. },
  17542. set: function (value) {
  17543. if (this._material === value) {
  17544. return;
  17545. }
  17546. this._material = value;
  17547. if (this.onMaterialChangedObservable.hasObservers) {
  17548. this.onMaterialChangedObservable.notifyObservers(this);
  17549. }
  17550. if (!this.subMeshes) {
  17551. return;
  17552. }
  17553. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17554. var subMesh = _a[_i];
  17555. subMesh.setEffect(null);
  17556. }
  17557. },
  17558. enumerable: true,
  17559. configurable: true
  17560. });
  17561. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17562. get: function () {
  17563. return this._receiveShadows;
  17564. },
  17565. set: function (value) {
  17566. if (this._receiveShadows === value) {
  17567. return;
  17568. }
  17569. this._receiveShadows = value;
  17570. this._markSubMeshesAsLightDirty();
  17571. },
  17572. enumerable: true,
  17573. configurable: true
  17574. });
  17575. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17576. get: function () {
  17577. return this._hasVertexAlpha;
  17578. },
  17579. set: function (value) {
  17580. if (this._hasVertexAlpha === value) {
  17581. return;
  17582. }
  17583. this._hasVertexAlpha = value;
  17584. this._markSubMeshesAsAttributesDirty();
  17585. this._markSubMeshesAsMiscDirty();
  17586. },
  17587. enumerable: true,
  17588. configurable: true
  17589. });
  17590. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17591. get: function () {
  17592. return this._useVertexColors;
  17593. },
  17594. set: function (value) {
  17595. if (this._useVertexColors === value) {
  17596. return;
  17597. }
  17598. this._useVertexColors = value;
  17599. this._markSubMeshesAsAttributesDirty();
  17600. },
  17601. enumerable: true,
  17602. configurable: true
  17603. });
  17604. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17605. get: function () {
  17606. return this._computeBonesUsingShaders;
  17607. },
  17608. set: function (value) {
  17609. if (this._computeBonesUsingShaders === value) {
  17610. return;
  17611. }
  17612. this._computeBonesUsingShaders = value;
  17613. this._markSubMeshesAsAttributesDirty();
  17614. },
  17615. enumerable: true,
  17616. configurable: true
  17617. });
  17618. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17619. get: function () {
  17620. return this._numBoneInfluencers;
  17621. },
  17622. set: function (value) {
  17623. if (this._numBoneInfluencers === value) {
  17624. return;
  17625. }
  17626. this._numBoneInfluencers = value;
  17627. this._markSubMeshesAsAttributesDirty();
  17628. },
  17629. enumerable: true,
  17630. configurable: true
  17631. });
  17632. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17633. get: function () {
  17634. return this._applyFog;
  17635. },
  17636. set: function (value) {
  17637. if (this._applyFog === value) {
  17638. return;
  17639. }
  17640. this._applyFog = value;
  17641. this._markSubMeshesAsMiscDirty();
  17642. },
  17643. enumerable: true,
  17644. configurable: true
  17645. });
  17646. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17647. get: function () {
  17648. return this._layerMask;
  17649. },
  17650. set: function (value) {
  17651. if (value === this._layerMask) {
  17652. return;
  17653. }
  17654. this._layerMask = value;
  17655. this._resyncLightSources();
  17656. },
  17657. enumerable: true,
  17658. configurable: true
  17659. });
  17660. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17661. get: function () {
  17662. return this._collisionMask;
  17663. },
  17664. set: function (mask) {
  17665. this._collisionMask = !isNaN(mask) ? mask : -1;
  17666. },
  17667. enumerable: true,
  17668. configurable: true
  17669. });
  17670. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17671. get: function () {
  17672. return this._collisionGroup;
  17673. },
  17674. set: function (mask) {
  17675. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17676. },
  17677. enumerable: true,
  17678. configurable: true
  17679. });
  17680. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17681. get: function () {
  17682. return null;
  17683. },
  17684. enumerable: true,
  17685. configurable: true
  17686. });
  17687. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17688. get: function () {
  17689. return this._skeleton;
  17690. },
  17691. set: function (value) {
  17692. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17693. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17694. }
  17695. if (value && value.needInitialSkinMatrix) {
  17696. value._registerMeshWithPoseMatrix(this);
  17697. }
  17698. this._skeleton = value;
  17699. if (!this._skeleton) {
  17700. this._bonesTransformMatrices = null;
  17701. }
  17702. this._markSubMeshesAsAttributesDirty();
  17703. },
  17704. enumerable: true,
  17705. configurable: true
  17706. });
  17707. /**
  17708. * Returns the string "AbstractMesh"
  17709. */
  17710. AbstractMesh.prototype.getClassName = function () {
  17711. return "AbstractMesh";
  17712. };
  17713. /**
  17714. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17715. */
  17716. AbstractMesh.prototype.toString = function (fullDetails) {
  17717. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17718. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17719. if (this._skeleton) {
  17720. ret += ", skeleton: " + this._skeleton.name;
  17721. }
  17722. if (fullDetails) {
  17723. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17724. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17725. }
  17726. return ret;
  17727. };
  17728. AbstractMesh.prototype._rebuild = function () {
  17729. if (this._occlusionQuery) {
  17730. this._occlusionQuery = null;
  17731. }
  17732. if (this._edgesRenderer) {
  17733. this._edgesRenderer._rebuild();
  17734. }
  17735. if (!this.subMeshes) {
  17736. return;
  17737. }
  17738. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17739. var subMesh = _a[_i];
  17740. subMesh._rebuild();
  17741. }
  17742. };
  17743. AbstractMesh.prototype._resyncLightSources = function () {
  17744. this._lightSources.length = 0;
  17745. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17746. var light = _a[_i];
  17747. if (!light.isEnabled()) {
  17748. continue;
  17749. }
  17750. if (light.canAffectMesh(this)) {
  17751. this._lightSources.push(light);
  17752. }
  17753. }
  17754. this._markSubMeshesAsLightDirty();
  17755. };
  17756. AbstractMesh.prototype._resyncLighSource = function (light) {
  17757. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17758. var index = this._lightSources.indexOf(light);
  17759. if (index === -1) {
  17760. if (!isIn) {
  17761. return;
  17762. }
  17763. this._lightSources.push(light);
  17764. }
  17765. else {
  17766. if (isIn) {
  17767. return;
  17768. }
  17769. this._lightSources.splice(index, 1);
  17770. }
  17771. this._markSubMeshesAsLightDirty();
  17772. };
  17773. AbstractMesh.prototype._removeLightSource = function (light) {
  17774. var index = this._lightSources.indexOf(light);
  17775. if (index === -1) {
  17776. return;
  17777. }
  17778. this._lightSources.splice(index, 1);
  17779. this._markSubMeshesAsLightDirty();
  17780. };
  17781. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17782. if (!this.subMeshes) {
  17783. return;
  17784. }
  17785. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17786. var subMesh = _a[_i];
  17787. if (subMesh._materialDefines) {
  17788. func(subMesh._materialDefines);
  17789. }
  17790. }
  17791. };
  17792. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17793. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17794. };
  17795. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17796. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17797. };
  17798. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17799. if (!this.subMeshes) {
  17800. return;
  17801. }
  17802. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17803. var subMesh = _a[_i];
  17804. var material = subMesh.getMaterial();
  17805. if (material) {
  17806. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17807. }
  17808. }
  17809. };
  17810. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17811. /**
  17812. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17813. * Default : (1.0, 1.0, 1.0)
  17814. */
  17815. get: function () {
  17816. return this._scaling;
  17817. },
  17818. /**
  17819. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17820. * Default : (1.0, 1.0, 1.0)
  17821. */
  17822. set: function (newScaling) {
  17823. this._scaling = newScaling;
  17824. if (this.physicsImpostor) {
  17825. this.physicsImpostor.forceUpdate();
  17826. }
  17827. },
  17828. enumerable: true,
  17829. configurable: true
  17830. });
  17831. // Methods
  17832. /**
  17833. * Disables the mesh edger rendering mode.
  17834. * Returns the AbstractMesh.
  17835. */
  17836. AbstractMesh.prototype.disableEdgesRendering = function () {
  17837. if (this._edgesRenderer) {
  17838. this._edgesRenderer.dispose();
  17839. this._edgesRenderer = null;
  17840. }
  17841. return this;
  17842. };
  17843. /**
  17844. * Enables the edge rendering mode on the mesh.
  17845. * This mode makes the mesh edges visible.
  17846. * Returns the AbstractMesh.
  17847. */
  17848. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17849. if (epsilon === void 0) { epsilon = 0.95; }
  17850. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17851. this.disableEdgesRendering();
  17852. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17853. return this;
  17854. };
  17855. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17856. /**
  17857. * Returns true if the mesh is blocked. Used by the class Mesh.
  17858. * Returns the boolean `false` by default.
  17859. */
  17860. get: function () {
  17861. return false;
  17862. },
  17863. enumerable: true,
  17864. configurable: true
  17865. });
  17866. /**
  17867. * Returns the mesh itself by default, used by the class Mesh.
  17868. * Returned type : AbstractMesh
  17869. */
  17870. AbstractMesh.prototype.getLOD = function (camera) {
  17871. return this;
  17872. };
  17873. /**
  17874. * Returns 0 by default, used by the class Mesh.
  17875. * Returns an integer.
  17876. */
  17877. AbstractMesh.prototype.getTotalVertices = function () {
  17878. return 0;
  17879. };
  17880. /**
  17881. * Returns null by default, used by the class Mesh.
  17882. * Returned type : integer array
  17883. */
  17884. AbstractMesh.prototype.getIndices = function () {
  17885. return null;
  17886. };
  17887. /**
  17888. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17889. * Returned type : float array or Float32Array
  17890. */
  17891. AbstractMesh.prototype.getVerticesData = function (kind) {
  17892. return null;
  17893. };
  17894. /**
  17895. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17896. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17897. * The `data` are either a numeric array either a Float32Array.
  17898. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17899. * 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).
  17900. * Note that a new underlying VertexBuffer object is created each call.
  17901. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17902. *
  17903. * Possible `kind` values :
  17904. * - BABYLON.VertexBuffer.PositionKind
  17905. * - BABYLON.VertexBuffer.UVKind
  17906. * - BABYLON.VertexBuffer.UV2Kind
  17907. * - BABYLON.VertexBuffer.UV3Kind
  17908. * - BABYLON.VertexBuffer.UV4Kind
  17909. * - BABYLON.VertexBuffer.UV5Kind
  17910. * - BABYLON.VertexBuffer.UV6Kind
  17911. * - BABYLON.VertexBuffer.ColorKind
  17912. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17913. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17914. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17915. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17916. *
  17917. * Returns the Mesh.
  17918. */
  17919. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17920. return this;
  17921. };
  17922. /**
  17923. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17924. * If the mesh has no geometry, it is simply returned as it is.
  17925. * The `data` are either a numeric array either a Float32Array.
  17926. * No new underlying VertexBuffer object is created.
  17927. * 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.
  17928. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17929. *
  17930. * Possible `kind` values :
  17931. * - BABYLON.VertexBuffer.PositionKind
  17932. * - BABYLON.VertexBuffer.UVKind
  17933. * - BABYLON.VertexBuffer.UV2Kind
  17934. * - BABYLON.VertexBuffer.UV3Kind
  17935. * - BABYLON.VertexBuffer.UV4Kind
  17936. * - BABYLON.VertexBuffer.UV5Kind
  17937. * - BABYLON.VertexBuffer.UV6Kind
  17938. * - BABYLON.VertexBuffer.ColorKind
  17939. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17940. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17941. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17942. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17943. *
  17944. * Returns the Mesh.
  17945. */
  17946. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17947. return this;
  17948. };
  17949. /**
  17950. * Sets the mesh indices.
  17951. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17952. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17953. * This method creates a new index buffer each call.
  17954. * Returns the Mesh.
  17955. */
  17956. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17957. return this;
  17958. };
  17959. /** Returns false by default, used by the class Mesh.
  17960. * Returns a boolean
  17961. */
  17962. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17963. return false;
  17964. };
  17965. /**
  17966. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17967. * Returns a BoundingInfo
  17968. */
  17969. AbstractMesh.prototype.getBoundingInfo = function () {
  17970. if (this._masterMesh) {
  17971. return this._masterMesh.getBoundingInfo();
  17972. }
  17973. if (!this._boundingInfo) {
  17974. // this._boundingInfo is being created here
  17975. this._updateBoundingInfo();
  17976. }
  17977. // cannot be null.
  17978. return this._boundingInfo;
  17979. };
  17980. /**
  17981. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17982. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17983. */
  17984. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17985. if (includeDescendants === void 0) { includeDescendants = true; }
  17986. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17987. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17988. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17989. if (maxDimension === 0) {
  17990. return this;
  17991. }
  17992. var scale = 1 / maxDimension;
  17993. this.scaling.scaleInPlace(scale);
  17994. return this;
  17995. };
  17996. /**
  17997. * Sets a mesh new object BoundingInfo.
  17998. * Returns the AbstractMesh.
  17999. */
  18000. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18001. this._boundingInfo = boundingInfo;
  18002. return this;
  18003. };
  18004. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18005. get: function () {
  18006. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18007. },
  18008. enumerable: true,
  18009. configurable: true
  18010. });
  18011. AbstractMesh.prototype._preActivate = function () {
  18012. };
  18013. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18014. };
  18015. AbstractMesh.prototype._activate = function (renderId) {
  18016. this._renderId = renderId;
  18017. };
  18018. /**
  18019. * Returns the latest update of the World matrix
  18020. * Returns a Matrix.
  18021. */
  18022. AbstractMesh.prototype.getWorldMatrix = function () {
  18023. if (this._masterMesh) {
  18024. return this._masterMesh.getWorldMatrix();
  18025. }
  18026. return _super.prototype.getWorldMatrix.call(this);
  18027. };
  18028. /**
  18029. * Returns the latest update of the World matrix determinant.
  18030. */
  18031. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18032. if (this._masterMesh) {
  18033. return this._masterMesh._getWorldMatrixDeterminant();
  18034. }
  18035. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18036. };
  18037. // ================================== Point of View Movement =================================
  18038. /**
  18039. * Perform relative position change from the point of view of behind the front of the mesh.
  18040. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18041. * Supports definition of mesh facing forward or backward.
  18042. * @param {number} amountRight
  18043. * @param {number} amountUp
  18044. * @param {number} amountForward
  18045. *
  18046. * Returns the AbstractMesh.
  18047. */
  18048. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18049. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18050. return this;
  18051. };
  18052. /**
  18053. * Calculate relative position change from the point of view of behind the front of the mesh.
  18054. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18055. * Supports definition of mesh facing forward or backward.
  18056. * @param {number} amountRight
  18057. * @param {number} amountUp
  18058. * @param {number} amountForward
  18059. *
  18060. * Returns a new Vector3.
  18061. */
  18062. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18063. var rotMatrix = new BABYLON.Matrix();
  18064. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18065. rotQuaternion.toRotationMatrix(rotMatrix);
  18066. var translationDelta = BABYLON.Vector3.Zero();
  18067. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18068. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18069. return translationDelta;
  18070. };
  18071. // ================================== Point of View Rotation =================================
  18072. /**
  18073. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18074. * Supports definition of mesh facing forward or backward.
  18075. * @param {number} flipBack
  18076. * @param {number} twirlClockwise
  18077. * @param {number} tiltRight
  18078. *
  18079. * Returns the AbstractMesh.
  18080. */
  18081. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18082. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18083. return this;
  18084. };
  18085. /**
  18086. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18087. * Supports definition of mesh facing forward or backward.
  18088. * @param {number} flipBack
  18089. * @param {number} twirlClockwise
  18090. * @param {number} tiltRight
  18091. *
  18092. * Returns a new Vector3.
  18093. */
  18094. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18095. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18096. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18097. };
  18098. /**
  18099. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18100. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18101. */
  18102. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18103. if (includeDescendants === void 0) { includeDescendants = true; }
  18104. this.computeWorldMatrix(true);
  18105. var min;
  18106. var max;
  18107. var boundingInfo = this.getBoundingInfo();
  18108. if (!this.subMeshes) {
  18109. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18110. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18111. }
  18112. else {
  18113. min = boundingInfo.boundingBox.minimumWorld;
  18114. max = boundingInfo.boundingBox.maximumWorld;
  18115. }
  18116. if (includeDescendants) {
  18117. var descendants = this.getDescendants(false);
  18118. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18119. var descendant = descendants_1[_i];
  18120. var childMesh = descendant;
  18121. childMesh.computeWorldMatrix(true);
  18122. //make sure we have the needed params to get mix and max
  18123. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18124. continue;
  18125. }
  18126. var childBoundingInfo = childMesh.getBoundingInfo();
  18127. var boundingBox = childBoundingInfo.boundingBox;
  18128. var minBox = boundingBox.minimumWorld;
  18129. var maxBox = boundingBox.maximumWorld;
  18130. BABYLON.Tools.CheckExtends(minBox, min, max);
  18131. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18132. }
  18133. }
  18134. return {
  18135. min: min,
  18136. max: max
  18137. };
  18138. };
  18139. /**
  18140. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18141. * Returns the AbstractMesh.
  18142. */
  18143. AbstractMesh.prototype._updateBoundingInfo = function () {
  18144. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18145. this._boundingInfo.update(this.worldMatrixFromCache);
  18146. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18147. return this;
  18148. };
  18149. /**
  18150. * Update a mesh's children BoundingInfo objects only.
  18151. * Returns the AbstractMesh.
  18152. */
  18153. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18154. if (!this.subMeshes) {
  18155. return this;
  18156. }
  18157. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18158. var subMesh = this.subMeshes[subIndex];
  18159. if (!subMesh.IsGlobal) {
  18160. subMesh.updateBoundingInfo(matrix);
  18161. }
  18162. }
  18163. return this;
  18164. };
  18165. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18166. // Bounding info
  18167. this._updateBoundingInfo();
  18168. };
  18169. /**
  18170. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18171. * A mesh is in the frustum if its bounding box intersects the frustum.
  18172. * Boolean returned.
  18173. */
  18174. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18175. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18176. };
  18177. /**
  18178. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18179. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18180. * Boolean returned.
  18181. */
  18182. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18183. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18184. ;
  18185. };
  18186. /**
  18187. * True if the mesh intersects another mesh or a SolidParticle object.
  18188. * 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)
  18189. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18190. * Returns a boolean.
  18191. */
  18192. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18193. if (precise === void 0) { precise = false; }
  18194. if (!this._boundingInfo || !mesh._boundingInfo) {
  18195. return false;
  18196. }
  18197. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18198. return true;
  18199. }
  18200. if (includeDescendants) {
  18201. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18202. var child = _a[_i];
  18203. if (child.intersectsMesh(mesh, precise, true)) {
  18204. return true;
  18205. }
  18206. }
  18207. }
  18208. return false;
  18209. };
  18210. /**
  18211. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18212. * Returns a boolean.
  18213. */
  18214. AbstractMesh.prototype.intersectsPoint = function (point) {
  18215. if (!this._boundingInfo) {
  18216. return false;
  18217. }
  18218. return this._boundingInfo.intersectsPoint(point);
  18219. };
  18220. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18221. return this.physicsImpostor;
  18222. };
  18223. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18224. if (camera === void 0) { camera = null; }
  18225. if (!camera) {
  18226. camera = this.getScene().activeCamera;
  18227. }
  18228. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18229. };
  18230. /**
  18231. * Returns the distance from the mesh to the active camera.
  18232. * Returns a float.
  18233. */
  18234. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18235. if (camera === void 0) { camera = null; }
  18236. if (!camera) {
  18237. camera = this.getScene().activeCamera;
  18238. }
  18239. return this.absolutePosition.subtract(camera.position).length();
  18240. };
  18241. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18242. if (!this.physicsImpostor) {
  18243. return this;
  18244. }
  18245. this.physicsImpostor.applyImpulse(force, contactPoint);
  18246. return this;
  18247. };
  18248. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18249. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18250. return this;
  18251. }
  18252. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18253. mainPivot: pivot1,
  18254. connectedPivot: pivot2,
  18255. nativeParams: options
  18256. });
  18257. return this;
  18258. };
  18259. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18260. // Collisions
  18261. /**
  18262. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18263. * Default `false`.
  18264. */
  18265. get: function () {
  18266. return this._checkCollisions;
  18267. },
  18268. set: function (collisionEnabled) {
  18269. this._checkCollisions = collisionEnabled;
  18270. if (this.getScene().workerCollisions) {
  18271. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18272. }
  18273. },
  18274. enumerable: true,
  18275. configurable: true
  18276. });
  18277. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18278. /**
  18279. * Gets Collider object used to compute collisions (not physics)
  18280. */
  18281. get: function () {
  18282. return this._collider;
  18283. },
  18284. enumerable: true,
  18285. configurable: true
  18286. });
  18287. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18288. var globalPosition = this.getAbsolutePosition();
  18289. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18290. if (!this._collider) {
  18291. this._collider = new BABYLON.Collider();
  18292. }
  18293. this._collider._radius = this.ellipsoid;
  18294. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18295. return this;
  18296. };
  18297. // Submeshes octree
  18298. /**
  18299. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18300. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18301. * Returns an Octree of submeshes.
  18302. */
  18303. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18304. if (maxCapacity === void 0) { maxCapacity = 64; }
  18305. if (maxDepth === void 0) { maxDepth = 2; }
  18306. if (!this._submeshesOctree) {
  18307. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18308. }
  18309. this.computeWorldMatrix(true);
  18310. var boundingInfo = this.getBoundingInfo();
  18311. // Update octree
  18312. var bbox = boundingInfo.boundingBox;
  18313. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18314. return this._submeshesOctree;
  18315. };
  18316. // Collisions
  18317. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18318. this._generatePointsArray();
  18319. if (!this._positions) {
  18320. return this;
  18321. }
  18322. // Transformation
  18323. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18324. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18325. subMesh._lastColliderWorldVertices = [];
  18326. subMesh._trianglePlanes = [];
  18327. var start = subMesh.verticesStart;
  18328. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18329. for (var i = start; i < end; i++) {
  18330. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18331. }
  18332. }
  18333. // Collide
  18334. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18335. if (collider.collisionFound) {
  18336. collider.collidedMesh = this;
  18337. }
  18338. return this;
  18339. };
  18340. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18341. var subMeshes;
  18342. var len;
  18343. // Octrees
  18344. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18345. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18346. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18347. len = intersections.length;
  18348. subMeshes = intersections.data;
  18349. }
  18350. else {
  18351. subMeshes = this.subMeshes;
  18352. len = subMeshes.length;
  18353. }
  18354. for (var index = 0; index < len; index++) {
  18355. var subMesh = subMeshes[index];
  18356. // Bounding test
  18357. if (len > 1 && !subMesh._checkCollision(collider))
  18358. continue;
  18359. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18360. }
  18361. return this;
  18362. };
  18363. AbstractMesh.prototype._checkCollision = function (collider) {
  18364. // Bounding box test
  18365. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18366. return this;
  18367. // Transformation matrix
  18368. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18369. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18370. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18371. return this;
  18372. };
  18373. // Picking
  18374. AbstractMesh.prototype._generatePointsArray = function () {
  18375. return false;
  18376. };
  18377. /**
  18378. * Checks if the passed Ray intersects with the mesh.
  18379. * Returns an object PickingInfo.
  18380. */
  18381. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18382. var pickingInfo = new BABYLON.PickingInfo();
  18383. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18384. return pickingInfo;
  18385. }
  18386. if (!this._generatePointsArray()) {
  18387. return pickingInfo;
  18388. }
  18389. var intersectInfo = null;
  18390. // Octrees
  18391. var subMeshes;
  18392. var len;
  18393. if (this._submeshesOctree && this.useOctreeForPicking) {
  18394. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18395. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18396. len = intersections.length;
  18397. subMeshes = intersections.data;
  18398. }
  18399. else {
  18400. subMeshes = this.subMeshes;
  18401. len = subMeshes.length;
  18402. }
  18403. for (var index = 0; index < len; index++) {
  18404. var subMesh = subMeshes[index];
  18405. // Bounding test
  18406. if (len > 1 && !subMesh.canIntersects(ray))
  18407. continue;
  18408. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18409. if (currentIntersectInfo) {
  18410. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18411. intersectInfo = currentIntersectInfo;
  18412. intersectInfo.subMeshId = index;
  18413. if (fastCheck) {
  18414. break;
  18415. }
  18416. }
  18417. }
  18418. }
  18419. if (intersectInfo) {
  18420. // Get picked point
  18421. var world = this.getWorldMatrix();
  18422. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18423. var direction = ray.direction.clone();
  18424. direction = direction.scale(intersectInfo.distance);
  18425. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18426. var pickedPoint = worldOrigin.add(worldDirection);
  18427. // Return result
  18428. pickingInfo.hit = true;
  18429. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18430. pickingInfo.pickedPoint = pickedPoint;
  18431. pickingInfo.pickedMesh = this;
  18432. pickingInfo.bu = intersectInfo.bu || 0;
  18433. pickingInfo.bv = intersectInfo.bv || 0;
  18434. pickingInfo.faceId = intersectInfo.faceId;
  18435. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18436. return pickingInfo;
  18437. }
  18438. return pickingInfo;
  18439. };
  18440. /**
  18441. * Clones the mesh, used by the class Mesh.
  18442. * Just returns `null` for an AbstractMesh.
  18443. */
  18444. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18445. return null;
  18446. };
  18447. /**
  18448. * Disposes all the mesh submeshes.
  18449. * Returns the AbstractMesh.
  18450. */
  18451. AbstractMesh.prototype.releaseSubMeshes = function () {
  18452. if (this.subMeshes) {
  18453. while (this.subMeshes.length) {
  18454. this.subMeshes[0].dispose();
  18455. }
  18456. }
  18457. else {
  18458. this.subMeshes = new Array();
  18459. }
  18460. return this;
  18461. };
  18462. /**
  18463. * Releases resources associated with this abstract mesh.
  18464. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18465. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18466. */
  18467. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18468. var _this = this;
  18469. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18470. var index;
  18471. // Smart Array Retainers.
  18472. this.getScene().freeActiveMeshes();
  18473. this.getScene().freeRenderingGroups();
  18474. // Action manager
  18475. if (this.actionManager !== undefined && this.actionManager !== null) {
  18476. this.actionManager.dispose();
  18477. this.actionManager = null;
  18478. }
  18479. // Skeleton
  18480. this.skeleton = null;
  18481. // Physics
  18482. if (this.physicsImpostor) {
  18483. this.physicsImpostor.dispose();
  18484. }
  18485. // Intersections in progress
  18486. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18487. var other = this._intersectionsInProgress[index];
  18488. var pos = other._intersectionsInProgress.indexOf(this);
  18489. other._intersectionsInProgress.splice(pos, 1);
  18490. }
  18491. this._intersectionsInProgress = [];
  18492. // Lights
  18493. var lights = this.getScene().lights;
  18494. lights.forEach(function (light) {
  18495. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18496. if (meshIndex !== -1) {
  18497. light.includedOnlyMeshes.splice(meshIndex, 1);
  18498. }
  18499. meshIndex = light.excludedMeshes.indexOf(_this);
  18500. if (meshIndex !== -1) {
  18501. light.excludedMeshes.splice(meshIndex, 1);
  18502. }
  18503. // Shadow generators
  18504. var generator = light.getShadowGenerator();
  18505. if (generator) {
  18506. var shadowMap = generator.getShadowMap();
  18507. if (shadowMap && shadowMap.renderList) {
  18508. meshIndex = shadowMap.renderList.indexOf(_this);
  18509. if (meshIndex !== -1) {
  18510. shadowMap.renderList.splice(meshIndex, 1);
  18511. }
  18512. }
  18513. }
  18514. });
  18515. // Edges
  18516. if (this._edgesRenderer) {
  18517. this._edgesRenderer.dispose();
  18518. this._edgesRenderer = null;
  18519. }
  18520. // SubMeshes
  18521. if (this.getClassName() !== "InstancedMesh") {
  18522. this.releaseSubMeshes();
  18523. }
  18524. // Octree
  18525. var sceneOctree = this.getScene().selectionOctree;
  18526. if (sceneOctree !== undefined && sceneOctree !== null) {
  18527. var index = sceneOctree.dynamicContent.indexOf(this);
  18528. if (index !== -1) {
  18529. sceneOctree.dynamicContent.splice(index, 1);
  18530. }
  18531. }
  18532. // Query
  18533. var engine = this.getScene().getEngine();
  18534. if (this._occlusionQuery) {
  18535. this._isOcclusionQueryInProgress = false;
  18536. engine.deleteQuery(this._occlusionQuery);
  18537. this._occlusionQuery = null;
  18538. }
  18539. // Engine
  18540. engine.wipeCaches();
  18541. // Remove from scene
  18542. this.getScene().removeMesh(this);
  18543. if (disposeMaterialAndTextures) {
  18544. if (this.material) {
  18545. this.material.dispose(false, true);
  18546. }
  18547. }
  18548. if (!doNotRecurse) {
  18549. // Particles
  18550. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18551. if (this.getScene().particleSystems[index].emitter === this) {
  18552. this.getScene().particleSystems[index].dispose();
  18553. index--;
  18554. }
  18555. }
  18556. }
  18557. // facet data
  18558. if (this._facetDataEnabled) {
  18559. this.disableFacetData();
  18560. }
  18561. this.onAfterWorldMatrixUpdateObservable.clear();
  18562. this.onCollideObservable.clear();
  18563. this.onCollisionPositionChangeObservable.clear();
  18564. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18565. };
  18566. /**
  18567. * Adds the passed mesh as a child to the current mesh.
  18568. * Returns the AbstractMesh.
  18569. */
  18570. AbstractMesh.prototype.addChild = function (mesh) {
  18571. mesh.setParent(this);
  18572. return this;
  18573. };
  18574. /**
  18575. * Removes the passed mesh from the current mesh children list.
  18576. * Returns the AbstractMesh.
  18577. */
  18578. AbstractMesh.prototype.removeChild = function (mesh) {
  18579. mesh.setParent(null);
  18580. return this;
  18581. };
  18582. // Facet data
  18583. /**
  18584. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18585. * Returns the AbstractMesh.
  18586. */
  18587. AbstractMesh.prototype._initFacetData = function () {
  18588. if (!this._facetNormals) {
  18589. this._facetNormals = new Array();
  18590. }
  18591. if (!this._facetPositions) {
  18592. this._facetPositions = new Array();
  18593. }
  18594. if (!this._facetPartitioning) {
  18595. this._facetPartitioning = new Array();
  18596. }
  18597. this._facetNb = (this.getIndices().length / 3) | 0;
  18598. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18599. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18600. for (var f = 0; f < this._facetNb; f++) {
  18601. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18602. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18603. }
  18604. this._facetDataEnabled = true;
  18605. return this;
  18606. };
  18607. /**
  18608. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18609. * This method can be called within the render loop.
  18610. * 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.
  18611. * Returns the AbstractMesh.
  18612. */
  18613. AbstractMesh.prototype.updateFacetData = function () {
  18614. if (!this._facetDataEnabled) {
  18615. this._initFacetData();
  18616. }
  18617. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18618. var indices = this.getIndices();
  18619. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18620. var bInfo = this.getBoundingInfo();
  18621. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18622. // init arrays, matrix and sort function on first call
  18623. this._facetDepthSortEnabled = true;
  18624. if (indices instanceof Uint16Array) {
  18625. this._depthSortedIndices = new Uint16Array(indices);
  18626. }
  18627. else if (indices instanceof Uint32Array) {
  18628. this._depthSortedIndices = new Uint32Array(indices);
  18629. }
  18630. else {
  18631. var needs32bits = false;
  18632. for (var i = 0; i < indices.length; i++) {
  18633. if (indices[i] > 65535) {
  18634. needs32bits = true;
  18635. break;
  18636. }
  18637. }
  18638. if (needs32bits) {
  18639. this._depthSortedIndices = new Uint32Array(indices);
  18640. }
  18641. else {
  18642. this._depthSortedIndices = new Uint16Array(indices);
  18643. }
  18644. }
  18645. this._facetDepthSortFunction = function (f1, f2) {
  18646. return (f2.sqDistance - f1.sqDistance);
  18647. };
  18648. if (!this._facetDepthSortFrom) {
  18649. var camera = this.getScene().activeCamera;
  18650. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18651. }
  18652. this._depthSortedFacets = [];
  18653. for (var f = 0; f < this._facetNb; f++) {
  18654. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18655. this._depthSortedFacets.push(depthSortedFacet);
  18656. }
  18657. this._invertedMatrix = BABYLON.Matrix.Identity();
  18658. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18659. }
  18660. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18661. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18662. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18663. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18664. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18665. this._subDiv.max = this._partitioningSubdivisions;
  18666. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18667. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18668. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18669. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18670. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18671. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18672. // set the parameters for ComputeNormals()
  18673. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18674. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18675. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18676. this._facetParameters.bInfo = bInfo;
  18677. this._facetParameters.bbSize = this._bbSize;
  18678. this._facetParameters.subDiv = this._subDiv;
  18679. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18680. this._facetParameters.depthSort = this._facetDepthSort;
  18681. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18682. this.computeWorldMatrix(true);
  18683. this._worldMatrix.invertToRef(this._invertedMatrix);
  18684. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18685. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18686. }
  18687. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18688. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18689. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18690. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18691. var l = (this._depthSortedIndices.length / 3) | 0;
  18692. for (var f = 0; f < l; f++) {
  18693. var sind = this._depthSortedFacets[f].ind;
  18694. this._depthSortedIndices[f * 3] = indices[sind];
  18695. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18696. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18697. }
  18698. this.updateIndices(this._depthSortedIndices);
  18699. }
  18700. return this;
  18701. };
  18702. /**
  18703. * Returns the facetLocalNormals array.
  18704. * The normals are expressed in the mesh local space.
  18705. */
  18706. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18707. if (!this._facetNormals) {
  18708. this.updateFacetData();
  18709. }
  18710. return this._facetNormals;
  18711. };
  18712. /**
  18713. * Returns the facetLocalPositions array.
  18714. * The facet positions are expressed in the mesh local space.
  18715. */
  18716. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18717. if (!this._facetPositions) {
  18718. this.updateFacetData();
  18719. }
  18720. return this._facetPositions;
  18721. };
  18722. /**
  18723. * Returns the facetLocalPartioning array.
  18724. */
  18725. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18726. if (!this._facetPartitioning) {
  18727. this.updateFacetData();
  18728. }
  18729. return this._facetPartitioning;
  18730. };
  18731. /**
  18732. * Returns the i-th facet position in the world system.
  18733. * This method allocates a new Vector3 per call.
  18734. */
  18735. AbstractMesh.prototype.getFacetPosition = function (i) {
  18736. var pos = BABYLON.Vector3.Zero();
  18737. this.getFacetPositionToRef(i, pos);
  18738. return pos;
  18739. };
  18740. /**
  18741. * Sets the reference Vector3 with the i-th facet position in the world system.
  18742. * Returns the AbstractMesh.
  18743. */
  18744. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18745. var localPos = (this.getFacetLocalPositions())[i];
  18746. var world = this.getWorldMatrix();
  18747. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18748. return this;
  18749. };
  18750. /**
  18751. * Returns the i-th facet normal in the world system.
  18752. * This method allocates a new Vector3 per call.
  18753. */
  18754. AbstractMesh.prototype.getFacetNormal = function (i) {
  18755. var norm = BABYLON.Vector3.Zero();
  18756. this.getFacetNormalToRef(i, norm);
  18757. return norm;
  18758. };
  18759. /**
  18760. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18761. * Returns the AbstractMesh.
  18762. */
  18763. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18764. var localNorm = (this.getFacetLocalNormals())[i];
  18765. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18766. return this;
  18767. };
  18768. /**
  18769. * 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).
  18770. */
  18771. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18772. var bInfo = this.getBoundingInfo();
  18773. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18774. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18775. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18776. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18777. return null;
  18778. }
  18779. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18780. };
  18781. /**
  18782. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18783. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18784. * 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.
  18785. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18786. * 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.
  18787. */
  18788. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18789. if (checkFace === void 0) { checkFace = false; }
  18790. if (facing === void 0) { facing = true; }
  18791. var world = this.getWorldMatrix();
  18792. var invMat = BABYLON.Tmp.Matrix[5];
  18793. world.invertToRef(invMat);
  18794. var invVect = BABYLON.Tmp.Vector3[8];
  18795. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18796. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18797. if (projected) {
  18798. // tranform the local computed projected vector to world coordinates
  18799. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18800. }
  18801. return closest;
  18802. };
  18803. /**
  18804. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18805. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18806. * 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.
  18807. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18808. * 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.
  18809. */
  18810. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18811. if (checkFace === void 0) { checkFace = false; }
  18812. if (facing === void 0) { facing = true; }
  18813. var closest = null;
  18814. var tmpx = 0.0;
  18815. var tmpy = 0.0;
  18816. var tmpz = 0.0;
  18817. var d = 0.0; // tmp dot facet normal * facet position
  18818. var t0 = 0.0;
  18819. var projx = 0.0;
  18820. var projy = 0.0;
  18821. var projz = 0.0;
  18822. // Get all the facets in the same partitioning block than (x, y, z)
  18823. var facetPositions = this.getFacetLocalPositions();
  18824. var facetNormals = this.getFacetLocalNormals();
  18825. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18826. if (!facetsInBlock) {
  18827. return null;
  18828. }
  18829. // Get the closest facet to (x, y, z)
  18830. var shortest = Number.MAX_VALUE; // init distance vars
  18831. var tmpDistance = shortest;
  18832. var fib; // current facet in the block
  18833. var norm; // current facet normal
  18834. var p0; // current facet barycenter position
  18835. // loop on all the facets in the current partitioning block
  18836. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18837. fib = facetsInBlock[idx];
  18838. norm = facetNormals[fib];
  18839. p0 = facetPositions[fib];
  18840. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18841. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18842. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18843. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18844. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18845. projx = x + norm.x * t0;
  18846. projy = y + norm.y * t0;
  18847. projz = z + norm.z * t0;
  18848. tmpx = projx - x;
  18849. tmpy = projy - y;
  18850. tmpz = projz - z;
  18851. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18852. if (tmpDistance < shortest) {
  18853. shortest = tmpDistance;
  18854. closest = fib;
  18855. if (projected) {
  18856. projected.x = projx;
  18857. projected.y = projy;
  18858. projected.z = projz;
  18859. }
  18860. }
  18861. }
  18862. }
  18863. return closest;
  18864. };
  18865. /**
  18866. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18867. */
  18868. AbstractMesh.prototype.getFacetDataParameters = function () {
  18869. return this._facetParameters;
  18870. };
  18871. /**
  18872. * Disables the feature FacetData and frees the related memory.
  18873. * Returns the AbstractMesh.
  18874. */
  18875. AbstractMesh.prototype.disableFacetData = function () {
  18876. if (this._facetDataEnabled) {
  18877. this._facetDataEnabled = false;
  18878. this._facetPositions = new Array();
  18879. this._facetNormals = new Array();
  18880. this._facetPartitioning = new Array();
  18881. this._facetParameters = null;
  18882. this._depthSortedIndices = new Uint32Array(0);
  18883. }
  18884. return this;
  18885. };
  18886. /**
  18887. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18888. * Returns the mesh.
  18889. */
  18890. AbstractMesh.prototype.updateIndices = function (indices) {
  18891. return this;
  18892. };
  18893. /**
  18894. * The mesh Geometry. Actually used by the Mesh object.
  18895. * Returns a blank geometry object.
  18896. */
  18897. /**
  18898. * Creates new normals data for the mesh.
  18899. * @param updatable.
  18900. */
  18901. AbstractMesh.prototype.createNormals = function (updatable) {
  18902. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18903. var indices = this.getIndices();
  18904. var normals;
  18905. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18906. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18907. }
  18908. else {
  18909. normals = [];
  18910. }
  18911. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18912. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18913. };
  18914. /**
  18915. * Align the mesh with a normal.
  18916. * Returns the mesh.
  18917. */
  18918. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18919. if (!upDirection) {
  18920. upDirection = BABYLON.Axis.Y;
  18921. }
  18922. var axisX = BABYLON.Tmp.Vector3[0];
  18923. var axisZ = BABYLON.Tmp.Vector3[1];
  18924. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18925. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18926. if (this.rotationQuaternion) {
  18927. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18928. }
  18929. else {
  18930. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18931. }
  18932. return this;
  18933. };
  18934. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18935. var engine = this.getEngine();
  18936. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18937. this._isOccluded = false;
  18938. return;
  18939. }
  18940. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18941. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18942. if (isOcclusionQueryAvailable) {
  18943. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18944. this._isOcclusionQueryInProgress = false;
  18945. this._occlusionInternalRetryCounter = 0;
  18946. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18947. }
  18948. else {
  18949. this._occlusionInternalRetryCounter++;
  18950. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18951. this._isOcclusionQueryInProgress = false;
  18952. this._occlusionInternalRetryCounter = 0;
  18953. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18954. // if strict continue the last state of the object.
  18955. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18956. }
  18957. else {
  18958. return;
  18959. }
  18960. }
  18961. }
  18962. var scene = this.getScene();
  18963. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18964. if (!this._occlusionQuery) {
  18965. this._occlusionQuery = engine.createQuery();
  18966. }
  18967. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18968. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18969. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18970. this._isOcclusionQueryInProgress = true;
  18971. };
  18972. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18973. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18974. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18975. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18976. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18977. return AbstractMesh;
  18978. }(BABYLON.TransformNode));
  18979. BABYLON.AbstractMesh = AbstractMesh;
  18980. })(BABYLON || (BABYLON = {}));
  18981. //# sourceMappingURL=babylon.abstractMesh.js.map
  18982. var BABYLON;
  18983. (function (BABYLON) {
  18984. /**
  18985. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18986. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18987. * 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.
  18988. */
  18989. var Light = /** @class */ (function (_super) {
  18990. __extends(Light, _super);
  18991. /**
  18992. * Creates a Light object in the scene.
  18993. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18994. * @param name The firendly name of the light
  18995. * @param scene The scene the light belongs too
  18996. */
  18997. function Light(name, scene) {
  18998. var _this = _super.call(this, name, scene) || this;
  18999. /**
  19000. * Diffuse gives the basic color to an object.
  19001. */
  19002. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19003. /**
  19004. * Specular produces a highlight color on an object.
  19005. * Note: This is note affecting PBR materials.
  19006. */
  19007. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19008. /**
  19009. * Strength of the light.
  19010. * Note: By default it is define in the framework own unit.
  19011. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19012. */
  19013. _this.intensity = 1.0;
  19014. /**
  19015. * Defines how far from the source the light is impacting in scene units.
  19016. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19017. */
  19018. _this.range = Number.MAX_VALUE;
  19019. /**
  19020. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19021. * of light.
  19022. */
  19023. _this._photometricScale = 1.0;
  19024. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19025. _this._radius = 0.00001;
  19026. /**
  19027. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19028. * exceeding the number allowed of the materials.
  19029. */
  19030. _this.renderPriority = 0;
  19031. /**
  19032. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19033. * the current shadow generator.
  19034. */
  19035. _this.shadowEnabled = true;
  19036. _this._excludeWithLayerMask = 0;
  19037. _this._includeOnlyWithLayerMask = 0;
  19038. _this._lightmapMode = 0;
  19039. /**
  19040. * @ignore Internal use only.
  19041. */
  19042. _this._excludedMeshesIds = new Array();
  19043. /**
  19044. * @ignore Internal use only.
  19045. */
  19046. _this._includedOnlyMeshesIds = new Array();
  19047. _this.getScene().addLight(_this);
  19048. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19049. _this._buildUniformLayout();
  19050. _this.includedOnlyMeshes = new Array();
  19051. _this.excludedMeshes = new Array();
  19052. _this._resyncMeshes();
  19053. return _this;
  19054. }
  19055. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19056. /**
  19057. * If every light affecting the material is in this lightmapMode,
  19058. * material.lightmapTexture adds or multiplies
  19059. * (depends on material.useLightmapAsShadowmap)
  19060. * after every other light calculations.
  19061. */
  19062. get: function () {
  19063. return Light._LIGHTMAP_DEFAULT;
  19064. },
  19065. enumerable: true,
  19066. configurable: true
  19067. });
  19068. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19069. /**
  19070. * material.lightmapTexture as only diffuse lighting from this light
  19071. * adds only specular lighting from this light
  19072. * adds dynamic shadows
  19073. */
  19074. get: function () {
  19075. return Light._LIGHTMAP_SPECULAR;
  19076. },
  19077. enumerable: true,
  19078. configurable: true
  19079. });
  19080. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19081. /**
  19082. * material.lightmapTexture as only lighting
  19083. * no light calculation from this light
  19084. * only adds dynamic shadows from this light
  19085. */
  19086. get: function () {
  19087. return Light._LIGHTMAP_SHADOWSONLY;
  19088. },
  19089. enumerable: true,
  19090. configurable: true
  19091. });
  19092. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19093. /**
  19094. * Each light type uses the default quantity according to its type:
  19095. * point/spot lights use luminous intensity
  19096. * directional lights use illuminance
  19097. */
  19098. get: function () {
  19099. return Light._INTENSITYMODE_AUTOMATIC;
  19100. },
  19101. enumerable: true,
  19102. configurable: true
  19103. });
  19104. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19105. /**
  19106. * lumen (lm)
  19107. */
  19108. get: function () {
  19109. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19110. },
  19111. enumerable: true,
  19112. configurable: true
  19113. });
  19114. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19115. /**
  19116. * candela (lm/sr)
  19117. */
  19118. get: function () {
  19119. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19120. },
  19121. enumerable: true,
  19122. configurable: true
  19123. });
  19124. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19125. /**
  19126. * lux (lm/m^2)
  19127. */
  19128. get: function () {
  19129. return Light._INTENSITYMODE_ILLUMINANCE;
  19130. },
  19131. enumerable: true,
  19132. configurable: true
  19133. });
  19134. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19135. /**
  19136. * nit (cd/m^2)
  19137. */
  19138. get: function () {
  19139. return Light._INTENSITYMODE_LUMINANCE;
  19140. },
  19141. enumerable: true,
  19142. configurable: true
  19143. });
  19144. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19145. /**
  19146. * Light type const id of the point light.
  19147. */
  19148. get: function () {
  19149. return Light._LIGHTTYPEID_POINTLIGHT;
  19150. },
  19151. enumerable: true,
  19152. configurable: true
  19153. });
  19154. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19155. /**
  19156. * Light type const id of the directional light.
  19157. */
  19158. get: function () {
  19159. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19160. },
  19161. enumerable: true,
  19162. configurable: true
  19163. });
  19164. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19165. /**
  19166. * Light type const id of the spot light.
  19167. */
  19168. get: function () {
  19169. return Light._LIGHTTYPEID_SPOTLIGHT;
  19170. },
  19171. enumerable: true,
  19172. configurable: true
  19173. });
  19174. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19175. /**
  19176. * Light type const id of the hemispheric light.
  19177. */
  19178. get: function () {
  19179. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19180. },
  19181. enumerable: true,
  19182. configurable: true
  19183. });
  19184. Object.defineProperty(Light.prototype, "intensityMode", {
  19185. /**
  19186. * Gets the photometric scale used to interpret the intensity.
  19187. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19188. */
  19189. get: function () {
  19190. return this._intensityMode;
  19191. },
  19192. /**
  19193. * Sets the photometric scale used to interpret the intensity.
  19194. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19195. */
  19196. set: function (value) {
  19197. this._intensityMode = value;
  19198. this._computePhotometricScale();
  19199. },
  19200. enumerable: true,
  19201. configurable: true
  19202. });
  19203. ;
  19204. ;
  19205. Object.defineProperty(Light.prototype, "radius", {
  19206. /**
  19207. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19208. */
  19209. get: function () {
  19210. return this._radius;
  19211. },
  19212. /**
  19213. * sets the light radius used by PBR Materials to simulate soft area lights.
  19214. */
  19215. set: function (value) {
  19216. this._radius = value;
  19217. this._computePhotometricScale();
  19218. },
  19219. enumerable: true,
  19220. configurable: true
  19221. });
  19222. ;
  19223. ;
  19224. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19225. /**
  19226. * Gets the only meshes impacted by this light.
  19227. */
  19228. get: function () {
  19229. return this._includedOnlyMeshes;
  19230. },
  19231. /**
  19232. * Sets the only meshes impacted by this light.
  19233. */
  19234. set: function (value) {
  19235. this._includedOnlyMeshes = value;
  19236. this._hookArrayForIncludedOnly(value);
  19237. },
  19238. enumerable: true,
  19239. configurable: true
  19240. });
  19241. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19242. /**
  19243. * Gets the meshes not impacted by this light.
  19244. */
  19245. get: function () {
  19246. return this._excludedMeshes;
  19247. },
  19248. /**
  19249. * Sets the meshes not impacted by this light.
  19250. */
  19251. set: function (value) {
  19252. this._excludedMeshes = value;
  19253. this._hookArrayForExcluded(value);
  19254. },
  19255. enumerable: true,
  19256. configurable: true
  19257. });
  19258. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19259. /**
  19260. * Gets the layer id use to find what meshes are not impacted by the light.
  19261. * Inactive if 0
  19262. */
  19263. get: function () {
  19264. return this._excludeWithLayerMask;
  19265. },
  19266. /**
  19267. * Sets the layer id use to find what meshes are not impacted by the light.
  19268. * Inactive if 0
  19269. */
  19270. set: function (value) {
  19271. this._excludeWithLayerMask = value;
  19272. this._resyncMeshes();
  19273. },
  19274. enumerable: true,
  19275. configurable: true
  19276. });
  19277. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19278. /**
  19279. * Gets the layer id use to find what meshes are impacted by the light.
  19280. * Inactive if 0
  19281. */
  19282. get: function () {
  19283. return this._includeOnlyWithLayerMask;
  19284. },
  19285. /**
  19286. * Sets the layer id use to find what meshes are impacted by the light.
  19287. * Inactive if 0
  19288. */
  19289. set: function (value) {
  19290. this._includeOnlyWithLayerMask = value;
  19291. this._resyncMeshes();
  19292. },
  19293. enumerable: true,
  19294. configurable: true
  19295. });
  19296. Object.defineProperty(Light.prototype, "lightmapMode", {
  19297. /**
  19298. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19299. */
  19300. get: function () {
  19301. return this._lightmapMode;
  19302. },
  19303. /**
  19304. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19305. */
  19306. set: function (value) {
  19307. if (this._lightmapMode === value) {
  19308. return;
  19309. }
  19310. this._lightmapMode = value;
  19311. this._markMeshesAsLightDirty();
  19312. },
  19313. enumerable: true,
  19314. configurable: true
  19315. });
  19316. /**
  19317. * Returns the string "Light".
  19318. * @returns the class name
  19319. */
  19320. Light.prototype.getClassName = function () {
  19321. return "Light";
  19322. };
  19323. /**
  19324. * Converts the light information to a readable string for debug purpose.
  19325. * @param fullDetails Supports for multiple levels of logging within scene loading
  19326. * @returns the human readable light info
  19327. */
  19328. Light.prototype.toString = function (fullDetails) {
  19329. var ret = "Name: " + this.name;
  19330. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19331. if (this.animations) {
  19332. for (var i = 0; i < this.animations.length; i++) {
  19333. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19334. }
  19335. }
  19336. if (fullDetails) {
  19337. }
  19338. return ret;
  19339. };
  19340. /**
  19341. * Set the enabled state of this node.
  19342. * @param value - the new enabled state
  19343. * @see isEnabled
  19344. */
  19345. Light.prototype.setEnabled = function (value) {
  19346. _super.prototype.setEnabled.call(this, value);
  19347. this._resyncMeshes();
  19348. };
  19349. /**
  19350. * Returns the Light associated shadow generator if any.
  19351. * @return the associated shadow generator.
  19352. */
  19353. Light.prototype.getShadowGenerator = function () {
  19354. return this._shadowGenerator;
  19355. };
  19356. /**
  19357. * Returns a Vector3, the absolute light position in the World.
  19358. * @returns the world space position of the light
  19359. */
  19360. Light.prototype.getAbsolutePosition = function () {
  19361. return BABYLON.Vector3.Zero();
  19362. };
  19363. /**
  19364. * Specifies if the light will affect the passed mesh.
  19365. * @param mesh The mesh to test against the light
  19366. * @return true the mesh is affected otherwise, false.
  19367. */
  19368. Light.prototype.canAffectMesh = function (mesh) {
  19369. if (!mesh) {
  19370. return true;
  19371. }
  19372. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19373. return false;
  19374. }
  19375. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19376. return false;
  19377. }
  19378. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19379. return false;
  19380. }
  19381. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19382. return false;
  19383. }
  19384. return true;
  19385. };
  19386. /**
  19387. * Computes and Returns the light World matrix.
  19388. * @returns the world matrix
  19389. */
  19390. Light.prototype.getWorldMatrix = function () {
  19391. this._currentRenderId = this.getScene().getRenderId();
  19392. var worldMatrix = this._getWorldMatrix();
  19393. if (this.parent && this.parent.getWorldMatrix) {
  19394. if (!this._parentedWorldMatrix) {
  19395. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19396. }
  19397. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19398. this._markSyncedWithParent();
  19399. return this._parentedWorldMatrix;
  19400. }
  19401. return worldMatrix;
  19402. };
  19403. /**
  19404. * Sort function to order lights for rendering.
  19405. * @param a First Light object to compare to second.
  19406. * @param b Second Light object to compare first.
  19407. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19408. */
  19409. Light.CompareLightsPriority = function (a, b) {
  19410. //shadow-casting lights have priority over non-shadow-casting lights
  19411. //the renderPrioirty is a secondary sort criterion
  19412. if (a.shadowEnabled !== b.shadowEnabled) {
  19413. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19414. }
  19415. return b.renderPriority - a.renderPriority;
  19416. };
  19417. /**
  19418. * Releases resources associated with this node.
  19419. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19420. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19421. */
  19422. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19423. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19424. if (this._shadowGenerator) {
  19425. this._shadowGenerator.dispose();
  19426. this._shadowGenerator = null;
  19427. }
  19428. // Animations
  19429. this.getScene().stopAnimation(this);
  19430. // Remove from meshes
  19431. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19432. var mesh = _a[_i];
  19433. mesh._removeLightSource(this);
  19434. }
  19435. this._uniformBuffer.dispose();
  19436. // Remove from scene
  19437. this.getScene().removeLight(this);
  19438. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19439. };
  19440. /**
  19441. * Returns the light type ID (integer).
  19442. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19443. */
  19444. Light.prototype.getTypeID = function () {
  19445. return 0;
  19446. };
  19447. /**
  19448. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19449. * @returns the scaled intensity in intensity mode unit
  19450. */
  19451. Light.prototype.getScaledIntensity = function () {
  19452. return this._photometricScale * this.intensity;
  19453. };
  19454. /**
  19455. * Returns a new Light object, named "name", from the current one.
  19456. * @param name The name of the cloned light
  19457. * @returns the new created light
  19458. */
  19459. Light.prototype.clone = function (name) {
  19460. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19461. if (!constructor) {
  19462. return null;
  19463. }
  19464. return BABYLON.SerializationHelper.Clone(constructor, this);
  19465. };
  19466. /**
  19467. * Serializes the current light into a Serialization object.
  19468. * @returns the serialized object.
  19469. */
  19470. Light.prototype.serialize = function () {
  19471. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19472. // Type
  19473. serializationObject.type = this.getTypeID();
  19474. // Parent
  19475. if (this.parent) {
  19476. serializationObject.parentId = this.parent.id;
  19477. }
  19478. // Inclusion / exclusions
  19479. if (this.excludedMeshes.length > 0) {
  19480. serializationObject.excludedMeshesIds = [];
  19481. this.excludedMeshes.forEach(function (mesh) {
  19482. serializationObject.excludedMeshesIds.push(mesh.id);
  19483. });
  19484. }
  19485. if (this.includedOnlyMeshes.length > 0) {
  19486. serializationObject.includedOnlyMeshesIds = [];
  19487. this.includedOnlyMeshes.forEach(function (mesh) {
  19488. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19489. });
  19490. }
  19491. // Animations
  19492. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19493. serializationObject.ranges = this.serializeAnimationRanges();
  19494. return serializationObject;
  19495. };
  19496. /**
  19497. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19498. * This new light is named "name" and added to the passed scene.
  19499. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19500. * @param name The friendly name of the light
  19501. * @param scene The scene the new light will belong to
  19502. * @returns the constructor function
  19503. */
  19504. Light.GetConstructorFromName = function (type, name, scene) {
  19505. switch (type) {
  19506. case 0:
  19507. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19508. case 1:
  19509. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19510. case 2:
  19511. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19512. case 3:
  19513. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19514. }
  19515. return null;
  19516. };
  19517. /**
  19518. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19519. * @param parsedLight The JSON representation of the light
  19520. * @param scene The scene to create the parsed light in
  19521. * @returns the created light after parsing
  19522. */
  19523. Light.Parse = function (parsedLight, scene) {
  19524. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19525. if (!constructor) {
  19526. return null;
  19527. }
  19528. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19529. // Inclusion / exclusions
  19530. if (parsedLight.excludedMeshesIds) {
  19531. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19532. }
  19533. if (parsedLight.includedOnlyMeshesIds) {
  19534. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19535. }
  19536. // Parent
  19537. if (parsedLight.parentId) {
  19538. light._waitingParentId = parsedLight.parentId;
  19539. }
  19540. // Animations
  19541. if (parsedLight.animations) {
  19542. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19543. var parsedAnimation = parsedLight.animations[animationIndex];
  19544. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19545. }
  19546. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19547. }
  19548. if (parsedLight.autoAnimate) {
  19549. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19550. }
  19551. return light;
  19552. };
  19553. Light.prototype._hookArrayForExcluded = function (array) {
  19554. var _this = this;
  19555. var oldPush = array.push;
  19556. array.push = function () {
  19557. var items = [];
  19558. for (var _i = 0; _i < arguments.length; _i++) {
  19559. items[_i] = arguments[_i];
  19560. }
  19561. var result = oldPush.apply(array, items);
  19562. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19563. var item = items_1[_a];
  19564. item._resyncLighSource(_this);
  19565. }
  19566. return result;
  19567. };
  19568. var oldSplice = array.splice;
  19569. array.splice = function (index, deleteCount) {
  19570. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19571. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19572. var item = deleted_1[_i];
  19573. item._resyncLighSource(_this);
  19574. }
  19575. return deleted;
  19576. };
  19577. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19578. var item = array_1[_i];
  19579. item._resyncLighSource(this);
  19580. }
  19581. };
  19582. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19583. var _this = this;
  19584. var oldPush = array.push;
  19585. array.push = function () {
  19586. var items = [];
  19587. for (var _i = 0; _i < arguments.length; _i++) {
  19588. items[_i] = arguments[_i];
  19589. }
  19590. var result = oldPush.apply(array, items);
  19591. _this._resyncMeshes();
  19592. return result;
  19593. };
  19594. var oldSplice = array.splice;
  19595. array.splice = function (index, deleteCount) {
  19596. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19597. _this._resyncMeshes();
  19598. return deleted;
  19599. };
  19600. this._resyncMeshes();
  19601. };
  19602. Light.prototype._resyncMeshes = function () {
  19603. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19604. var mesh = _a[_i];
  19605. mesh._resyncLighSource(this);
  19606. }
  19607. };
  19608. /**
  19609. * Forces the meshes to update their light related information in their rendering used effects
  19610. * @ignore Internal Use Only
  19611. */
  19612. Light.prototype._markMeshesAsLightDirty = function () {
  19613. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19614. var mesh = _a[_i];
  19615. if (mesh._lightSources.indexOf(this) !== -1) {
  19616. mesh._markSubMeshesAsLightDirty();
  19617. }
  19618. }
  19619. };
  19620. /**
  19621. * Recomputes the cached photometric scale if needed.
  19622. */
  19623. Light.prototype._computePhotometricScale = function () {
  19624. this._photometricScale = this._getPhotometricScale();
  19625. this.getScene().resetCachedMaterial();
  19626. };
  19627. /**
  19628. * Returns the Photometric Scale according to the light type and intensity mode.
  19629. */
  19630. Light.prototype._getPhotometricScale = function () {
  19631. var photometricScale = 0.0;
  19632. var lightTypeID = this.getTypeID();
  19633. //get photometric mode
  19634. var photometricMode = this.intensityMode;
  19635. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19636. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19637. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19638. }
  19639. else {
  19640. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19641. }
  19642. }
  19643. //compute photometric scale
  19644. switch (lightTypeID) {
  19645. case Light.LIGHTTYPEID_POINTLIGHT:
  19646. case Light.LIGHTTYPEID_SPOTLIGHT:
  19647. switch (photometricMode) {
  19648. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19649. photometricScale = 1.0 / (4.0 * Math.PI);
  19650. break;
  19651. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19652. photometricScale = 1.0;
  19653. break;
  19654. case Light.INTENSITYMODE_LUMINANCE:
  19655. photometricScale = this.radius * this.radius;
  19656. break;
  19657. }
  19658. break;
  19659. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19660. switch (photometricMode) {
  19661. case Light.INTENSITYMODE_ILLUMINANCE:
  19662. photometricScale = 1.0;
  19663. break;
  19664. case Light.INTENSITYMODE_LUMINANCE:
  19665. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19666. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19667. var apexAngleRadians = this.radius;
  19668. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19669. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19670. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19671. photometricScale = solidAngle;
  19672. break;
  19673. }
  19674. break;
  19675. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19676. // No fall off in hemisperic light.
  19677. photometricScale = 1.0;
  19678. break;
  19679. }
  19680. return photometricScale;
  19681. };
  19682. /**
  19683. * Reorder the light in the scene according to their defined priority.
  19684. * @ignore Internal Use Only
  19685. */
  19686. Light.prototype._reorderLightsInScene = function () {
  19687. var scene = this.getScene();
  19688. if (this._renderPriority != 0) {
  19689. scene.requireLightSorting = true;
  19690. }
  19691. this.getScene().sortLightsByPriority();
  19692. };
  19693. //lightmapMode Consts
  19694. Light._LIGHTMAP_DEFAULT = 0;
  19695. Light._LIGHTMAP_SPECULAR = 1;
  19696. Light._LIGHTMAP_SHADOWSONLY = 2;
  19697. // Intensity Mode Consts
  19698. Light._INTENSITYMODE_AUTOMATIC = 0;
  19699. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19700. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19701. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19702. Light._INTENSITYMODE_LUMINANCE = 4;
  19703. // Light types ids const.
  19704. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19705. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19706. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19707. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19708. __decorate([
  19709. BABYLON.serializeAsColor3()
  19710. ], Light.prototype, "diffuse", void 0);
  19711. __decorate([
  19712. BABYLON.serializeAsColor3()
  19713. ], Light.prototype, "specular", void 0);
  19714. __decorate([
  19715. BABYLON.serialize()
  19716. ], Light.prototype, "intensity", void 0);
  19717. __decorate([
  19718. BABYLON.serialize()
  19719. ], Light.prototype, "range", void 0);
  19720. __decorate([
  19721. BABYLON.serialize()
  19722. ], Light.prototype, "intensityMode", null);
  19723. __decorate([
  19724. BABYLON.serialize()
  19725. ], Light.prototype, "radius", null);
  19726. __decorate([
  19727. BABYLON.serialize()
  19728. ], Light.prototype, "_renderPriority", void 0);
  19729. __decorate([
  19730. BABYLON.expandToProperty("_reorderLightsInScene")
  19731. ], Light.prototype, "renderPriority", void 0);
  19732. __decorate([
  19733. BABYLON.serialize()
  19734. ], Light.prototype, "shadowEnabled", void 0);
  19735. __decorate([
  19736. BABYLON.serialize("excludeWithLayerMask")
  19737. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19738. __decorate([
  19739. BABYLON.serialize("includeOnlyWithLayerMask")
  19740. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19741. __decorate([
  19742. BABYLON.serialize("lightmapMode")
  19743. ], Light.prototype, "_lightmapMode", void 0);
  19744. return Light;
  19745. }(BABYLON.Node));
  19746. BABYLON.Light = Light;
  19747. })(BABYLON || (BABYLON = {}));
  19748. //# sourceMappingURL=babylon.light.js.map
  19749. var BABYLON;
  19750. (function (BABYLON) {
  19751. var Camera = /** @class */ (function (_super) {
  19752. __extends(Camera, _super);
  19753. function Camera(name, position, scene) {
  19754. var _this = _super.call(this, name, scene) || this;
  19755. /**
  19756. * The vector the camera should consider as up.
  19757. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19758. */
  19759. _this.upVector = BABYLON.Vector3.Up();
  19760. _this.orthoLeft = null;
  19761. _this.orthoRight = null;
  19762. _this.orthoBottom = null;
  19763. _this.orthoTop = null;
  19764. /**
  19765. * FOV is set in Radians. (default is 0.8)
  19766. */
  19767. _this.fov = 0.8;
  19768. _this.minZ = 1;
  19769. _this.maxZ = 10000.0;
  19770. _this.inertia = 0.9;
  19771. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19772. _this.isIntermediate = false;
  19773. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19774. /**
  19775. * Restricts the camera to viewing objects with the same layerMask.
  19776. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19777. */
  19778. _this.layerMask = 0x0FFFFFFF;
  19779. /**
  19780. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19781. */
  19782. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19783. // Camera rig members
  19784. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19785. _this._rigCameras = new Array();
  19786. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19787. _this._skipRendering = false;
  19788. _this.customRenderTargets = new Array();
  19789. // Observables
  19790. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19791. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19792. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19793. _this.onRestoreStateObservable = new BABYLON.Observable();
  19794. // Cache
  19795. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19796. _this._projectionMatrix = new BABYLON.Matrix();
  19797. _this._doNotComputeProjectionMatrix = false;
  19798. _this._postProcesses = new Array();
  19799. _this._transformMatrix = BABYLON.Matrix.Zero();
  19800. _this._activeMeshes = new BABYLON.SmartArray(256);
  19801. _this._globalPosition = BABYLON.Vector3.Zero();
  19802. _this._refreshFrustumPlanes = true;
  19803. _this.getScene().addCamera(_this);
  19804. if (!_this.getScene().activeCamera) {
  19805. _this.getScene().activeCamera = _this;
  19806. }
  19807. _this.position = position;
  19808. return _this;
  19809. }
  19810. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19811. get: function () {
  19812. return Camera._PERSPECTIVE_CAMERA;
  19813. },
  19814. enumerable: true,
  19815. configurable: true
  19816. });
  19817. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19818. get: function () {
  19819. return Camera._ORTHOGRAPHIC_CAMERA;
  19820. },
  19821. enumerable: true,
  19822. configurable: true
  19823. });
  19824. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19825. /**
  19826. * This is the default FOV mode for perspective cameras.
  19827. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19828. *
  19829. */
  19830. get: function () {
  19831. return Camera._FOVMODE_VERTICAL_FIXED;
  19832. },
  19833. enumerable: true,
  19834. configurable: true
  19835. });
  19836. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19837. /**
  19838. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19839. *
  19840. */
  19841. get: function () {
  19842. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19843. },
  19844. enumerable: true,
  19845. configurable: true
  19846. });
  19847. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19848. get: function () {
  19849. return Camera._RIG_MODE_NONE;
  19850. },
  19851. enumerable: true,
  19852. configurable: true
  19853. });
  19854. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19855. get: function () {
  19856. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19857. },
  19858. enumerable: true,
  19859. configurable: true
  19860. });
  19861. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19862. get: function () {
  19863. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19864. },
  19865. enumerable: true,
  19866. configurable: true
  19867. });
  19868. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19869. get: function () {
  19870. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19871. },
  19872. enumerable: true,
  19873. configurable: true
  19874. });
  19875. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19876. get: function () {
  19877. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19878. },
  19879. enumerable: true,
  19880. configurable: true
  19881. });
  19882. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19883. get: function () {
  19884. return Camera._RIG_MODE_VR;
  19885. },
  19886. enumerable: true,
  19887. configurable: true
  19888. });
  19889. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19890. get: function () {
  19891. return Camera._RIG_MODE_WEBVR;
  19892. },
  19893. enumerable: true,
  19894. configurable: true
  19895. });
  19896. /**
  19897. * Store current camera state (fov, position, etc..)
  19898. */
  19899. Camera.prototype.storeState = function () {
  19900. this._stateStored = true;
  19901. this._storedFov = this.fov;
  19902. return this;
  19903. };
  19904. /**
  19905. * Restores the camera state values if it has been stored. You must call storeState() first
  19906. */
  19907. Camera.prototype._restoreStateValues = function () {
  19908. if (!this._stateStored) {
  19909. return false;
  19910. }
  19911. this.fov = this._storedFov;
  19912. return true;
  19913. };
  19914. /**
  19915. * Restored camera state. You must call storeState() first
  19916. */
  19917. Camera.prototype.restoreState = function () {
  19918. if (this._restoreStateValues()) {
  19919. this.onRestoreStateObservable.notifyObservers(this);
  19920. return true;
  19921. }
  19922. return false;
  19923. };
  19924. Camera.prototype.getClassName = function () {
  19925. return "Camera";
  19926. };
  19927. /**
  19928. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19929. */
  19930. Camera.prototype.toString = function (fullDetails) {
  19931. var ret = "Name: " + this.name;
  19932. ret += ", type: " + this.getClassName();
  19933. if (this.animations) {
  19934. for (var i = 0; i < this.animations.length; i++) {
  19935. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19936. }
  19937. }
  19938. if (fullDetails) {
  19939. }
  19940. return ret;
  19941. };
  19942. Object.defineProperty(Camera.prototype, "globalPosition", {
  19943. get: function () {
  19944. return this._globalPosition;
  19945. },
  19946. enumerable: true,
  19947. configurable: true
  19948. });
  19949. Camera.prototype.getActiveMeshes = function () {
  19950. return this._activeMeshes;
  19951. };
  19952. Camera.prototype.isActiveMesh = function (mesh) {
  19953. return (this._activeMeshes.indexOf(mesh) !== -1);
  19954. };
  19955. //Cache
  19956. Camera.prototype._initCache = function () {
  19957. _super.prototype._initCache.call(this);
  19958. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19959. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19960. this._cache.mode = undefined;
  19961. this._cache.minZ = undefined;
  19962. this._cache.maxZ = undefined;
  19963. this._cache.fov = undefined;
  19964. this._cache.fovMode = undefined;
  19965. this._cache.aspectRatio = undefined;
  19966. this._cache.orthoLeft = undefined;
  19967. this._cache.orthoRight = undefined;
  19968. this._cache.orthoBottom = undefined;
  19969. this._cache.orthoTop = undefined;
  19970. this._cache.renderWidth = undefined;
  19971. this._cache.renderHeight = undefined;
  19972. };
  19973. Camera.prototype._updateCache = function (ignoreParentClass) {
  19974. if (!ignoreParentClass) {
  19975. _super.prototype._updateCache.call(this);
  19976. }
  19977. this._cache.position.copyFrom(this.position);
  19978. this._cache.upVector.copyFrom(this.upVector);
  19979. };
  19980. // Synchronized
  19981. Camera.prototype._isSynchronized = function () {
  19982. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19983. };
  19984. Camera.prototype._isSynchronizedViewMatrix = function () {
  19985. if (!_super.prototype._isSynchronized.call(this))
  19986. return false;
  19987. return this._cache.position.equals(this.position)
  19988. && this._cache.upVector.equals(this.upVector)
  19989. && this.isSynchronizedWithParent();
  19990. };
  19991. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19992. var check = this._cache.mode === this.mode
  19993. && this._cache.minZ === this.minZ
  19994. && this._cache.maxZ === this.maxZ;
  19995. if (!check) {
  19996. return false;
  19997. }
  19998. var engine = this.getEngine();
  19999. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20000. check = this._cache.fov === this.fov
  20001. && this._cache.fovMode === this.fovMode
  20002. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20003. }
  20004. else {
  20005. check = this._cache.orthoLeft === this.orthoLeft
  20006. && this._cache.orthoRight === this.orthoRight
  20007. && this._cache.orthoBottom === this.orthoBottom
  20008. && this._cache.orthoTop === this.orthoTop
  20009. && this._cache.renderWidth === engine.getRenderWidth()
  20010. && this._cache.renderHeight === engine.getRenderHeight();
  20011. }
  20012. return check;
  20013. };
  20014. // Controls
  20015. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20016. };
  20017. Camera.prototype.detachControl = function (element) {
  20018. };
  20019. Camera.prototype.update = function () {
  20020. this._checkInputs();
  20021. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20022. this._updateRigCameras();
  20023. }
  20024. };
  20025. Camera.prototype._checkInputs = function () {
  20026. this.onAfterCheckInputsObservable.notifyObservers(this);
  20027. };
  20028. Object.defineProperty(Camera.prototype, "rigCameras", {
  20029. get: function () {
  20030. return this._rigCameras;
  20031. },
  20032. enumerable: true,
  20033. configurable: true
  20034. });
  20035. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20036. get: function () {
  20037. return this._rigPostProcess;
  20038. },
  20039. enumerable: true,
  20040. configurable: true
  20041. });
  20042. /**
  20043. * Internal, gets the first post proces.
  20044. * @returns the first post process to be run on this camera.
  20045. */
  20046. Camera.prototype._getFirstPostProcess = function () {
  20047. for (var pp in this._postProcesses) {
  20048. if (this._postProcesses[pp] !== null) {
  20049. return this._postProcesses[pp];
  20050. }
  20051. }
  20052. return null;
  20053. };
  20054. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20055. // invalidate framebuffer
  20056. var firstPostProcess = this._getFirstPostProcess();
  20057. if (firstPostProcess) {
  20058. firstPostProcess.markTextureDirty();
  20059. }
  20060. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20061. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20062. var cam = this._rigCameras[i];
  20063. var rigPostProcess = cam._rigPostProcess;
  20064. // for VR rig, there does not have to be a post process
  20065. if (rigPostProcess) {
  20066. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20067. if (isPass) {
  20068. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20069. cam.isIntermediate = this._postProcesses.length === 0;
  20070. }
  20071. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20072. rigPostProcess.markTextureDirty();
  20073. }
  20074. else {
  20075. cam._postProcesses = this._postProcesses.slice(0);
  20076. }
  20077. }
  20078. };
  20079. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20080. if (insertAt === void 0) { insertAt = null; }
  20081. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20082. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20083. return 0;
  20084. }
  20085. if (insertAt == null || insertAt < 0) {
  20086. this._postProcesses.push(postProcess);
  20087. }
  20088. else if (this._postProcesses[insertAt] === null) {
  20089. this._postProcesses[insertAt] = postProcess;
  20090. }
  20091. else {
  20092. this._postProcesses.splice(insertAt, 0, postProcess);
  20093. }
  20094. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20095. return this._postProcesses.indexOf(postProcess);
  20096. };
  20097. Camera.prototype.detachPostProcess = function (postProcess) {
  20098. var idx = this._postProcesses.indexOf(postProcess);
  20099. if (idx !== -1) {
  20100. this._postProcesses[idx] = null;
  20101. }
  20102. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20103. };
  20104. Camera.prototype.getWorldMatrix = function () {
  20105. if (!this._worldMatrix) {
  20106. this._worldMatrix = BABYLON.Matrix.Identity();
  20107. }
  20108. var viewMatrix = this.getViewMatrix();
  20109. viewMatrix.invertToRef(this._worldMatrix);
  20110. return this._worldMatrix;
  20111. };
  20112. Camera.prototype._getViewMatrix = function () {
  20113. return BABYLON.Matrix.Identity();
  20114. };
  20115. Camera.prototype.getViewMatrix = function (force) {
  20116. if (!force && this._isSynchronizedViewMatrix()) {
  20117. return this._computedViewMatrix;
  20118. }
  20119. this.updateCache();
  20120. this._computedViewMatrix = this._getViewMatrix();
  20121. this._currentRenderId = this.getScene().getRenderId();
  20122. this._refreshFrustumPlanes = true;
  20123. if (!this.parent || !this.parent.getWorldMatrix) {
  20124. this._globalPosition.copyFrom(this.position);
  20125. }
  20126. else {
  20127. if (!this._worldMatrix) {
  20128. this._worldMatrix = BABYLON.Matrix.Identity();
  20129. }
  20130. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20131. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20132. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20133. this._computedViewMatrix.invert();
  20134. this._markSyncedWithParent();
  20135. }
  20136. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20137. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20138. }
  20139. this.onViewMatrixChangedObservable.notifyObservers(this);
  20140. return this._computedViewMatrix;
  20141. };
  20142. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20143. this._doNotComputeProjectionMatrix = true;
  20144. if (projection !== undefined) {
  20145. this._projectionMatrix = projection;
  20146. }
  20147. };
  20148. ;
  20149. Camera.prototype.unfreezeProjectionMatrix = function () {
  20150. this._doNotComputeProjectionMatrix = false;
  20151. };
  20152. ;
  20153. Camera.prototype.getProjectionMatrix = function (force) {
  20154. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20155. return this._projectionMatrix;
  20156. }
  20157. // Cache
  20158. this._cache.mode = this.mode;
  20159. this._cache.minZ = this.minZ;
  20160. this._cache.maxZ = this.maxZ;
  20161. // Matrix
  20162. this._refreshFrustumPlanes = true;
  20163. var engine = this.getEngine();
  20164. var scene = this.getScene();
  20165. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20166. this._cache.fov = this.fov;
  20167. this._cache.fovMode = this.fovMode;
  20168. this._cache.aspectRatio = engine.getAspectRatio(this);
  20169. if (this.minZ <= 0) {
  20170. this.minZ = 0.1;
  20171. }
  20172. if (scene.useRightHandedSystem) {
  20173. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20174. }
  20175. else {
  20176. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20177. }
  20178. }
  20179. else {
  20180. var halfWidth = engine.getRenderWidth() / 2.0;
  20181. var halfHeight = engine.getRenderHeight() / 2.0;
  20182. if (scene.useRightHandedSystem) {
  20183. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20184. }
  20185. else {
  20186. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20187. }
  20188. this._cache.orthoLeft = this.orthoLeft;
  20189. this._cache.orthoRight = this.orthoRight;
  20190. this._cache.orthoBottom = this.orthoBottom;
  20191. this._cache.orthoTop = this.orthoTop;
  20192. this._cache.renderWidth = engine.getRenderWidth();
  20193. this._cache.renderHeight = engine.getRenderHeight();
  20194. }
  20195. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20196. return this._projectionMatrix;
  20197. };
  20198. Camera.prototype.getTranformationMatrix = function () {
  20199. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20200. return this._transformMatrix;
  20201. };
  20202. Camera.prototype.updateFrustumPlanes = function () {
  20203. if (!this._refreshFrustumPlanes) {
  20204. return;
  20205. }
  20206. this.getTranformationMatrix();
  20207. if (!this._frustumPlanes) {
  20208. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20209. }
  20210. else {
  20211. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20212. }
  20213. this._refreshFrustumPlanes = false;
  20214. };
  20215. Camera.prototype.isInFrustum = function (target) {
  20216. this.updateFrustumPlanes();
  20217. return target.isInFrustum(this._frustumPlanes);
  20218. };
  20219. Camera.prototype.isCompletelyInFrustum = function (target) {
  20220. this.updateFrustumPlanes();
  20221. return target.isCompletelyInFrustum(this._frustumPlanes);
  20222. };
  20223. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20224. if (length === void 0) { length = 100; }
  20225. if (!transform) {
  20226. transform = this.getWorldMatrix();
  20227. }
  20228. if (!origin) {
  20229. origin = this.position;
  20230. }
  20231. var forward = new BABYLON.Vector3(0, 0, 1);
  20232. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20233. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20234. return new BABYLON.Ray(origin, direction, length);
  20235. };
  20236. /**
  20237. * Releases resources associated with this node.
  20238. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20239. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20240. */
  20241. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20242. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20243. // Observables
  20244. this.onViewMatrixChangedObservable.clear();
  20245. this.onProjectionMatrixChangedObservable.clear();
  20246. this.onAfterCheckInputsObservable.clear();
  20247. this.onRestoreStateObservable.clear();
  20248. // Inputs
  20249. if (this.inputs) {
  20250. this.inputs.clear();
  20251. }
  20252. // Animations
  20253. this.getScene().stopAnimation(this);
  20254. // Remove from scene
  20255. this.getScene().removeCamera(this);
  20256. while (this._rigCameras.length > 0) {
  20257. var camera = this._rigCameras.pop();
  20258. if (camera) {
  20259. camera.dispose();
  20260. }
  20261. }
  20262. // Postprocesses
  20263. if (this._rigPostProcess) {
  20264. this._rigPostProcess.dispose(this);
  20265. this._rigPostProcess = null;
  20266. this._postProcesses = [];
  20267. }
  20268. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20269. this._rigPostProcess = null;
  20270. this._postProcesses = [];
  20271. }
  20272. else {
  20273. var i = this._postProcesses.length;
  20274. while (--i >= 0) {
  20275. var postProcess = this._postProcesses[i];
  20276. if (postProcess) {
  20277. postProcess.dispose(this);
  20278. }
  20279. }
  20280. }
  20281. // Render targets
  20282. var i = this.customRenderTargets.length;
  20283. while (--i >= 0) {
  20284. this.customRenderTargets[i].dispose();
  20285. }
  20286. this.customRenderTargets = [];
  20287. // Active Meshes
  20288. this._activeMeshes.dispose();
  20289. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20290. };
  20291. Object.defineProperty(Camera.prototype, "leftCamera", {
  20292. // ---- Camera rigs section ----
  20293. get: function () {
  20294. if (this._rigCameras.length < 1) {
  20295. return null;
  20296. }
  20297. return this._rigCameras[0];
  20298. },
  20299. enumerable: true,
  20300. configurable: true
  20301. });
  20302. Object.defineProperty(Camera.prototype, "rightCamera", {
  20303. get: function () {
  20304. if (this._rigCameras.length < 2) {
  20305. return null;
  20306. }
  20307. return this._rigCameras[1];
  20308. },
  20309. enumerable: true,
  20310. configurable: true
  20311. });
  20312. Camera.prototype.getLeftTarget = function () {
  20313. if (this._rigCameras.length < 1) {
  20314. return null;
  20315. }
  20316. return this._rigCameras[0].getTarget();
  20317. };
  20318. Camera.prototype.getRightTarget = function () {
  20319. if (this._rigCameras.length < 2) {
  20320. return null;
  20321. }
  20322. return this._rigCameras[1].getTarget();
  20323. };
  20324. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20325. if (this.cameraRigMode === mode) {
  20326. return;
  20327. }
  20328. while (this._rigCameras.length > 0) {
  20329. var camera = this._rigCameras.pop();
  20330. if (camera) {
  20331. camera.dispose();
  20332. }
  20333. }
  20334. this.cameraRigMode = mode;
  20335. this._cameraRigParams = {};
  20336. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20337. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20338. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20339. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20340. // create the rig cameras, unless none
  20341. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20342. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20343. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20344. if (leftCamera && rightCamera) {
  20345. this._rigCameras.push(leftCamera);
  20346. this._rigCameras.push(rightCamera);
  20347. }
  20348. }
  20349. switch (this.cameraRigMode) {
  20350. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20351. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20352. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20353. break;
  20354. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20355. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20356. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20357. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20358. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20359. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20360. break;
  20361. case Camera.RIG_MODE_VR:
  20362. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20363. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20364. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20365. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20366. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20367. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20368. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20369. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20370. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20371. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20372. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20373. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20374. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20375. if (metrics.compensateDistortion) {
  20376. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20377. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20378. }
  20379. break;
  20380. case Camera.RIG_MODE_WEBVR:
  20381. if (rigParams.vrDisplay) {
  20382. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20383. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20384. //Left eye
  20385. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20386. this._rigCameras[0].setCameraRigParameter("left", true);
  20387. //leaving this for future reference
  20388. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20389. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20390. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20391. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20392. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20393. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20394. this._rigCameras[0].parent = this;
  20395. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20396. //Right eye
  20397. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20398. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20399. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20400. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20401. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20402. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20403. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20404. this._rigCameras[1].parent = this;
  20405. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20406. if (Camera.UseAlternateWebVRRendering) {
  20407. this._rigCameras[1]._skipRendering = true;
  20408. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20409. }
  20410. }
  20411. break;
  20412. }
  20413. this._cascadePostProcessesToRigCams();
  20414. this.update();
  20415. };
  20416. Camera.prototype._getVRProjectionMatrix = function () {
  20417. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20418. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20419. return this._projectionMatrix;
  20420. };
  20421. Camera.prototype._updateCameraRotationMatrix = function () {
  20422. //Here for WebVR
  20423. };
  20424. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20425. //Here for WebVR
  20426. };
  20427. /**
  20428. * This function MUST be overwritten by the different WebVR cameras available.
  20429. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20430. */
  20431. Camera.prototype._getWebVRProjectionMatrix = function () {
  20432. return BABYLON.Matrix.Identity();
  20433. };
  20434. /**
  20435. * This function MUST be overwritten by the different WebVR cameras available.
  20436. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20437. */
  20438. Camera.prototype._getWebVRViewMatrix = function () {
  20439. return BABYLON.Matrix.Identity();
  20440. };
  20441. Camera.prototype.setCameraRigParameter = function (name, value) {
  20442. if (!this._cameraRigParams) {
  20443. this._cameraRigParams = {};
  20444. }
  20445. this._cameraRigParams[name] = value;
  20446. //provisionnally:
  20447. if (name === "interaxialDistance") {
  20448. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20449. }
  20450. };
  20451. /**
  20452. * needs to be overridden by children so sub has required properties to be copied
  20453. */
  20454. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20455. return null;
  20456. };
  20457. /**
  20458. * May need to be overridden by children
  20459. */
  20460. Camera.prototype._updateRigCameras = function () {
  20461. for (var i = 0; i < this._rigCameras.length; i++) {
  20462. this._rigCameras[i].minZ = this.minZ;
  20463. this._rigCameras[i].maxZ = this.maxZ;
  20464. this._rigCameras[i].fov = this.fov;
  20465. }
  20466. // only update viewport when ANAGLYPH
  20467. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20468. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20469. }
  20470. };
  20471. Camera.prototype._setupInputs = function () {
  20472. };
  20473. Camera.prototype.serialize = function () {
  20474. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20475. // Type
  20476. serializationObject.type = this.getClassName();
  20477. // Parent
  20478. if (this.parent) {
  20479. serializationObject.parentId = this.parent.id;
  20480. }
  20481. if (this.inputs) {
  20482. this.inputs.serialize(serializationObject);
  20483. }
  20484. // Animations
  20485. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20486. serializationObject.ranges = this.serializeAnimationRanges();
  20487. return serializationObject;
  20488. };
  20489. Camera.prototype.clone = function (name) {
  20490. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20491. };
  20492. Camera.prototype.getDirection = function (localAxis) {
  20493. var result = BABYLON.Vector3.Zero();
  20494. this.getDirectionToRef(localAxis, result);
  20495. return result;
  20496. };
  20497. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20498. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20499. };
  20500. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20501. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20502. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20503. switch (type) {
  20504. case "ArcRotateCamera":
  20505. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20506. case "DeviceOrientationCamera":
  20507. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20508. case "FollowCamera":
  20509. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20510. case "ArcFollowCamera":
  20511. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20512. case "GamepadCamera":
  20513. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20514. case "TouchCamera":
  20515. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20516. case "VirtualJoysticksCamera":
  20517. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20518. case "WebVRFreeCamera":
  20519. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20520. case "WebVRGamepadCamera":
  20521. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20522. case "VRDeviceOrientationFreeCamera":
  20523. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20524. case "VRDeviceOrientationGamepadCamera":
  20525. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20526. case "AnaglyphArcRotateCamera":
  20527. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20528. case "AnaglyphFreeCamera":
  20529. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20530. case "AnaglyphGamepadCamera":
  20531. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20532. case "AnaglyphUniversalCamera":
  20533. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20534. case "StereoscopicArcRotateCamera":
  20535. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20536. case "StereoscopicFreeCamera":
  20537. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20538. case "StereoscopicGamepadCamera":
  20539. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20540. case "StereoscopicUniversalCamera":
  20541. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20542. case "FreeCamera":// Forcing Universal here
  20543. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20544. default:// Universal Camera is the default value
  20545. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20546. }
  20547. };
  20548. Camera.prototype.computeWorldMatrix = function () {
  20549. return this.getWorldMatrix();
  20550. };
  20551. Camera.Parse = function (parsedCamera, scene) {
  20552. var type = parsedCamera.type;
  20553. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20554. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20555. // Parent
  20556. if (parsedCamera.parentId) {
  20557. camera._waitingParentId = parsedCamera.parentId;
  20558. }
  20559. //If camera has an input manager, let it parse inputs settings
  20560. if (camera.inputs) {
  20561. camera.inputs.parse(parsedCamera);
  20562. camera._setupInputs();
  20563. }
  20564. if (camera.setPosition) {
  20565. camera.position.copyFromFloats(0, 0, 0);
  20566. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20567. }
  20568. // Target
  20569. if (parsedCamera.target) {
  20570. if (camera.setTarget) {
  20571. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20572. }
  20573. }
  20574. // Apply 3d rig, when found
  20575. if (parsedCamera.cameraRigMode) {
  20576. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20577. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20578. }
  20579. // Animations
  20580. if (parsedCamera.animations) {
  20581. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20582. var parsedAnimation = parsedCamera.animations[animationIndex];
  20583. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20584. }
  20585. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20586. }
  20587. if (parsedCamera.autoAnimate) {
  20588. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20589. }
  20590. return camera;
  20591. };
  20592. // Statics
  20593. Camera._PERSPECTIVE_CAMERA = 0;
  20594. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20595. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20596. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20597. Camera._RIG_MODE_NONE = 0;
  20598. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20599. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20600. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20601. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20602. Camera._RIG_MODE_VR = 20;
  20603. Camera._RIG_MODE_WEBVR = 21;
  20604. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20605. Camera.UseAlternateWebVRRendering = false;
  20606. __decorate([
  20607. BABYLON.serializeAsVector3()
  20608. ], Camera.prototype, "position", void 0);
  20609. __decorate([
  20610. BABYLON.serializeAsVector3()
  20611. ], Camera.prototype, "upVector", void 0);
  20612. __decorate([
  20613. BABYLON.serialize()
  20614. ], Camera.prototype, "orthoLeft", void 0);
  20615. __decorate([
  20616. BABYLON.serialize()
  20617. ], Camera.prototype, "orthoRight", void 0);
  20618. __decorate([
  20619. BABYLON.serialize()
  20620. ], Camera.prototype, "orthoBottom", void 0);
  20621. __decorate([
  20622. BABYLON.serialize()
  20623. ], Camera.prototype, "orthoTop", void 0);
  20624. __decorate([
  20625. BABYLON.serialize()
  20626. ], Camera.prototype, "fov", void 0);
  20627. __decorate([
  20628. BABYLON.serialize()
  20629. ], Camera.prototype, "minZ", void 0);
  20630. __decorate([
  20631. BABYLON.serialize()
  20632. ], Camera.prototype, "maxZ", void 0);
  20633. __decorate([
  20634. BABYLON.serialize()
  20635. ], Camera.prototype, "inertia", void 0);
  20636. __decorate([
  20637. BABYLON.serialize()
  20638. ], Camera.prototype, "mode", void 0);
  20639. __decorate([
  20640. BABYLON.serialize()
  20641. ], Camera.prototype, "layerMask", void 0);
  20642. __decorate([
  20643. BABYLON.serialize()
  20644. ], Camera.prototype, "fovMode", void 0);
  20645. __decorate([
  20646. BABYLON.serialize()
  20647. ], Camera.prototype, "cameraRigMode", void 0);
  20648. __decorate([
  20649. BABYLON.serialize()
  20650. ], Camera.prototype, "interaxialDistance", void 0);
  20651. __decorate([
  20652. BABYLON.serialize()
  20653. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20654. return Camera;
  20655. }(BABYLON.Node));
  20656. BABYLON.Camera = Camera;
  20657. })(BABYLON || (BABYLON = {}));
  20658. //# sourceMappingURL=babylon.camera.js.map
  20659. var BABYLON;
  20660. (function (BABYLON) {
  20661. var RenderingManager = /** @class */ (function () {
  20662. function RenderingManager(scene) {
  20663. this._renderingGroups = new Array();
  20664. this._autoClearDepthStencil = {};
  20665. this._customOpaqueSortCompareFn = {};
  20666. this._customAlphaTestSortCompareFn = {};
  20667. this._customTransparentSortCompareFn = {};
  20668. this._renderinGroupInfo = null;
  20669. this._scene = scene;
  20670. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20671. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20672. }
  20673. }
  20674. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20675. if (depth === void 0) { depth = true; }
  20676. if (stencil === void 0) { stencil = true; }
  20677. if (this._depthStencilBufferAlreadyCleaned) {
  20678. return;
  20679. }
  20680. this._scene.getEngine().clear(null, false, depth, stencil);
  20681. this._depthStencilBufferAlreadyCleaned = true;
  20682. };
  20683. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20684. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20685. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20686. var info = null;
  20687. if (observable) {
  20688. if (!this._renderinGroupInfo) {
  20689. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20690. }
  20691. info = this._renderinGroupInfo;
  20692. info.scene = this._scene;
  20693. info.camera = this._scene.activeCamera;
  20694. }
  20695. // Dispatch sprites
  20696. if (renderSprites) {
  20697. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20698. var manager = this._scene.spriteManagers[index];
  20699. this.dispatchSprites(manager);
  20700. }
  20701. }
  20702. // Render
  20703. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20704. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20705. var renderingGroup = this._renderingGroups[index];
  20706. if (!renderingGroup && !observable)
  20707. continue;
  20708. var renderingGroupMask = 0;
  20709. // Fire PRECLEAR stage
  20710. if (observable && info) {
  20711. renderingGroupMask = Math.pow(2, index);
  20712. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20713. info.renderingGroupId = index;
  20714. observable.notifyObservers(info, renderingGroupMask);
  20715. }
  20716. // Clear depth/stencil if needed
  20717. if (RenderingManager.AUTOCLEAR) {
  20718. var autoClear = this._autoClearDepthStencil[index];
  20719. if (autoClear && autoClear.autoClear) {
  20720. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20721. }
  20722. }
  20723. if (observable && info) {
  20724. // Fire PREOPAQUE stage
  20725. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20726. observable.notifyObservers(info, renderingGroupMask);
  20727. // Fire PRETRANSPARENT stage
  20728. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20729. observable.notifyObservers(info, renderingGroupMask);
  20730. }
  20731. if (renderingGroup)
  20732. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20733. // Fire POSTTRANSPARENT stage
  20734. if (observable && info) {
  20735. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20736. observable.notifyObservers(info, renderingGroupMask);
  20737. }
  20738. }
  20739. };
  20740. RenderingManager.prototype.reset = function () {
  20741. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20742. var renderingGroup = this._renderingGroups[index];
  20743. if (renderingGroup) {
  20744. renderingGroup.prepare();
  20745. }
  20746. }
  20747. };
  20748. RenderingManager.prototype.dispose = function () {
  20749. this.freeRenderingGroups();
  20750. this._renderingGroups.length = 0;
  20751. };
  20752. /**
  20753. * Clear the info related to rendering groups preventing retention points during dispose.
  20754. */
  20755. RenderingManager.prototype.freeRenderingGroups = function () {
  20756. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20757. var renderingGroup = this._renderingGroups[index];
  20758. if (renderingGroup) {
  20759. renderingGroup.dispose();
  20760. }
  20761. }
  20762. };
  20763. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20764. if (this._renderingGroups[renderingGroupId] === undefined) {
  20765. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20766. }
  20767. };
  20768. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20769. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20770. this._prepareRenderingGroup(renderingGroupId);
  20771. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20772. };
  20773. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20774. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20775. this._prepareRenderingGroup(renderingGroupId);
  20776. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20777. };
  20778. /**
  20779. * @param subMesh The submesh to dispatch
  20780. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20781. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20782. */
  20783. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20784. if (mesh === undefined) {
  20785. mesh = subMesh.getMesh();
  20786. }
  20787. var renderingGroupId = mesh.renderingGroupId || 0;
  20788. this._prepareRenderingGroup(renderingGroupId);
  20789. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20790. };
  20791. /**
  20792. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20793. * This allowed control for front to back rendering or reversly depending of the special needs.
  20794. *
  20795. * @param renderingGroupId The rendering group id corresponding to its index
  20796. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20797. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20798. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20799. */
  20800. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20801. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20802. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20803. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20804. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20805. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20806. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20807. if (this._renderingGroups[renderingGroupId]) {
  20808. var group = this._renderingGroups[renderingGroupId];
  20809. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20810. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20811. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20812. }
  20813. };
  20814. /**
  20815. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20816. *
  20817. * @param renderingGroupId The rendering group id corresponding to its index
  20818. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20819. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20820. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20821. */
  20822. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20823. if (depth === void 0) { depth = true; }
  20824. if (stencil === void 0) { stencil = true; }
  20825. this._autoClearDepthStencil[renderingGroupId] = {
  20826. autoClear: autoClearDepthStencil,
  20827. depth: depth,
  20828. stencil: stencil
  20829. };
  20830. };
  20831. /**
  20832. * The max id used for rendering groups (not included)
  20833. */
  20834. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20835. /**
  20836. * The min id used for rendering groups (included)
  20837. */
  20838. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20839. /**
  20840. * Used to globally prevent autoclearing scenes.
  20841. */
  20842. RenderingManager.AUTOCLEAR = true;
  20843. return RenderingManager;
  20844. }());
  20845. BABYLON.RenderingManager = RenderingManager;
  20846. })(BABYLON || (BABYLON = {}));
  20847. //# sourceMappingURL=babylon.renderingManager.js.map
  20848. var BABYLON;
  20849. (function (BABYLON) {
  20850. var RenderingGroup = /** @class */ (function () {
  20851. /**
  20852. * Creates a new rendering group.
  20853. * @param index The rendering group index
  20854. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20855. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20856. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20857. */
  20858. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20859. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20860. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20861. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20862. this.index = index;
  20863. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20864. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20865. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20866. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20867. this._particleSystems = new BABYLON.SmartArray(256);
  20868. this._spriteManagers = new BABYLON.SmartArray(256);
  20869. this._edgesRenderers = new BABYLON.SmartArray(16);
  20870. this._scene = scene;
  20871. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20872. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20873. this.transparentSortCompareFn = transparentSortCompareFn;
  20874. }
  20875. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20876. /**
  20877. * Set the opaque sort comparison function.
  20878. * If null the sub meshes will be render in the order they were created
  20879. */
  20880. set: function (value) {
  20881. this._opaqueSortCompareFn = value;
  20882. if (value) {
  20883. this._renderOpaque = this.renderOpaqueSorted;
  20884. }
  20885. else {
  20886. this._renderOpaque = RenderingGroup.renderUnsorted;
  20887. }
  20888. },
  20889. enumerable: true,
  20890. configurable: true
  20891. });
  20892. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20893. /**
  20894. * Set the alpha test sort comparison function.
  20895. * If null the sub meshes will be render in the order they were created
  20896. */
  20897. set: function (value) {
  20898. this._alphaTestSortCompareFn = value;
  20899. if (value) {
  20900. this._renderAlphaTest = this.renderAlphaTestSorted;
  20901. }
  20902. else {
  20903. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20904. }
  20905. },
  20906. enumerable: true,
  20907. configurable: true
  20908. });
  20909. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20910. /**
  20911. * Set the transparent sort comparison function.
  20912. * If null the sub meshes will be render in the order they were created
  20913. */
  20914. set: function (value) {
  20915. if (value) {
  20916. this._transparentSortCompareFn = value;
  20917. }
  20918. else {
  20919. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20920. }
  20921. this._renderTransparent = this.renderTransparentSorted;
  20922. },
  20923. enumerable: true,
  20924. configurable: true
  20925. });
  20926. /**
  20927. * Render all the sub meshes contained in the group.
  20928. * @param customRenderFunction Used to override the default render behaviour of the group.
  20929. * @returns true if rendered some submeshes.
  20930. */
  20931. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20932. if (customRenderFunction) {
  20933. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20934. return;
  20935. }
  20936. var engine = this._scene.getEngine();
  20937. // Depth only
  20938. if (this._depthOnlySubMeshes.length !== 0) {
  20939. engine.setColorWrite(false);
  20940. this._renderAlphaTest(this._depthOnlySubMeshes);
  20941. engine.setColorWrite(true);
  20942. }
  20943. // Opaque
  20944. if (this._opaqueSubMeshes.length !== 0) {
  20945. this._renderOpaque(this._opaqueSubMeshes);
  20946. }
  20947. // Alpha test
  20948. if (this._alphaTestSubMeshes.length !== 0) {
  20949. this._renderAlphaTest(this._alphaTestSubMeshes);
  20950. }
  20951. var stencilState = engine.getStencilBuffer();
  20952. engine.setStencilBuffer(false);
  20953. // Sprites
  20954. if (renderSprites) {
  20955. this._renderSprites();
  20956. }
  20957. // Particles
  20958. if (renderParticles) {
  20959. this._renderParticles(activeMeshes);
  20960. }
  20961. if (this.onBeforeTransparentRendering) {
  20962. this.onBeforeTransparentRendering();
  20963. }
  20964. // Transparent
  20965. if (this._transparentSubMeshes.length !== 0) {
  20966. this._renderTransparent(this._transparentSubMeshes);
  20967. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20968. }
  20969. // Set back stencil to false in case it changes before the edge renderer.
  20970. engine.setStencilBuffer(false);
  20971. // Edges
  20972. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20973. this._edgesRenderers.data[edgesRendererIndex].render();
  20974. }
  20975. // Restore Stencil state.
  20976. engine.setStencilBuffer(stencilState);
  20977. };
  20978. /**
  20979. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20980. * @param subMeshes The submeshes to render
  20981. */
  20982. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20983. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20984. };
  20985. /**
  20986. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20987. * @param subMeshes The submeshes to render
  20988. */
  20989. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20990. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20991. };
  20992. /**
  20993. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20994. * @param subMeshes The submeshes to render
  20995. */
  20996. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20997. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20998. };
  20999. /**
  21000. * Renders the submeshes in a specified order.
  21001. * @param subMeshes The submeshes to sort before render
  21002. * @param sortCompareFn The comparison function use to sort
  21003. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21004. * @param transparent Specifies to activate blending if true
  21005. */
  21006. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21007. var subIndex = 0;
  21008. var subMesh;
  21009. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21010. for (; subIndex < subMeshes.length; subIndex++) {
  21011. subMesh = subMeshes.data[subIndex];
  21012. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21013. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21014. }
  21015. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21016. if (sortCompareFn) {
  21017. sortedArray.sort(sortCompareFn);
  21018. }
  21019. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21020. subMesh = sortedArray[subIndex];
  21021. if (transparent) {
  21022. var material = subMesh.getMaterial();
  21023. if (material && material.needDepthPrePass) {
  21024. var engine = material.getScene().getEngine();
  21025. engine.setColorWrite(false);
  21026. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21027. subMesh.render(false);
  21028. engine.setColorWrite(true);
  21029. }
  21030. }
  21031. subMesh.render(transparent);
  21032. }
  21033. };
  21034. /**
  21035. * Renders the submeshes in the order they were dispatched (no sort applied).
  21036. * @param subMeshes The submeshes to render
  21037. */
  21038. RenderingGroup.renderUnsorted = function (subMeshes) {
  21039. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21040. var submesh = subMeshes.data[subIndex];
  21041. submesh.render(false);
  21042. }
  21043. };
  21044. /**
  21045. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21046. * are rendered back to front if in the same alpha index.
  21047. *
  21048. * @param a The first submesh
  21049. * @param b The second submesh
  21050. * @returns The result of the comparison
  21051. */
  21052. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21053. // Alpha index first
  21054. if (a._alphaIndex > b._alphaIndex) {
  21055. return 1;
  21056. }
  21057. if (a._alphaIndex < b._alphaIndex) {
  21058. return -1;
  21059. }
  21060. // Then distance to camera
  21061. return RenderingGroup.backToFrontSortCompare(a, b);
  21062. };
  21063. /**
  21064. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21065. * are rendered back to front.
  21066. *
  21067. * @param a The first submesh
  21068. * @param b The second submesh
  21069. * @returns The result of the comparison
  21070. */
  21071. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21072. // Then distance to camera
  21073. if (a._distanceToCamera < b._distanceToCamera) {
  21074. return 1;
  21075. }
  21076. if (a._distanceToCamera > b._distanceToCamera) {
  21077. return -1;
  21078. }
  21079. return 0;
  21080. };
  21081. /**
  21082. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21083. * are rendered front to back (prevent overdraw).
  21084. *
  21085. * @param a The first submesh
  21086. * @param b The second submesh
  21087. * @returns The result of the comparison
  21088. */
  21089. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21090. // Then distance to camera
  21091. if (a._distanceToCamera < b._distanceToCamera) {
  21092. return -1;
  21093. }
  21094. if (a._distanceToCamera > b._distanceToCamera) {
  21095. return 1;
  21096. }
  21097. return 0;
  21098. };
  21099. /**
  21100. * Resets the different lists of submeshes to prepare a new frame.
  21101. */
  21102. RenderingGroup.prototype.prepare = function () {
  21103. this._opaqueSubMeshes.reset();
  21104. this._transparentSubMeshes.reset();
  21105. this._alphaTestSubMeshes.reset();
  21106. this._depthOnlySubMeshes.reset();
  21107. this._particleSystems.reset();
  21108. this._spriteManagers.reset();
  21109. this._edgesRenderers.reset();
  21110. };
  21111. RenderingGroup.prototype.dispose = function () {
  21112. this._opaqueSubMeshes.dispose();
  21113. this._transparentSubMeshes.dispose();
  21114. this._alphaTestSubMeshes.dispose();
  21115. this._depthOnlySubMeshes.dispose();
  21116. this._particleSystems.dispose();
  21117. this._spriteManagers.dispose();
  21118. this._edgesRenderers.dispose();
  21119. };
  21120. /**
  21121. * Inserts the submesh in its correct queue depending on its material.
  21122. * @param subMesh The submesh to dispatch
  21123. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21124. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21125. */
  21126. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21127. // Get mesh and materials if not provided
  21128. if (mesh === undefined) {
  21129. mesh = subMesh.getMesh();
  21130. }
  21131. if (material === undefined) {
  21132. material = subMesh.getMaterial();
  21133. }
  21134. if (material === null || material === undefined) {
  21135. return;
  21136. }
  21137. if (material.needAlphaBlendingForMesh(mesh)) {
  21138. this._transparentSubMeshes.push(subMesh);
  21139. }
  21140. else if (material.needAlphaTesting()) {
  21141. if (material.needDepthPrePass) {
  21142. this._depthOnlySubMeshes.push(subMesh);
  21143. }
  21144. this._alphaTestSubMeshes.push(subMesh);
  21145. }
  21146. else {
  21147. if (material.needDepthPrePass) {
  21148. this._depthOnlySubMeshes.push(subMesh);
  21149. }
  21150. this._opaqueSubMeshes.push(subMesh); // Opaque
  21151. }
  21152. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21153. this._edgesRenderers.push(mesh._edgesRenderer);
  21154. }
  21155. };
  21156. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21157. this._spriteManagers.push(spriteManager);
  21158. };
  21159. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21160. this._particleSystems.push(particleSystem);
  21161. };
  21162. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21163. if (this._particleSystems.length === 0) {
  21164. return;
  21165. }
  21166. // Particles
  21167. var activeCamera = this._scene.activeCamera;
  21168. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21169. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21170. var particleSystem = this._particleSystems.data[particleIndex];
  21171. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21172. continue;
  21173. }
  21174. var emitter = particleSystem.emitter;
  21175. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21176. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21177. }
  21178. }
  21179. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21180. };
  21181. RenderingGroup.prototype._renderSprites = function () {
  21182. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21183. return;
  21184. }
  21185. // Sprites
  21186. var activeCamera = this._scene.activeCamera;
  21187. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21188. for (var id = 0; id < this._spriteManagers.length; id++) {
  21189. var spriteManager = this._spriteManagers.data[id];
  21190. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21191. spriteManager.render();
  21192. }
  21193. }
  21194. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21195. };
  21196. return RenderingGroup;
  21197. }());
  21198. BABYLON.RenderingGroup = RenderingGroup;
  21199. })(BABYLON || (BABYLON = {}));
  21200. //# sourceMappingURL=babylon.renderingGroup.js.map
  21201. var BABYLON;
  21202. (function (BABYLON) {
  21203. var ClickInfo = /** @class */ (function () {
  21204. function ClickInfo() {
  21205. this._singleClick = false;
  21206. this._doubleClick = false;
  21207. this._hasSwiped = false;
  21208. this._ignore = false;
  21209. }
  21210. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21211. get: function () {
  21212. return this._singleClick;
  21213. },
  21214. set: function (b) {
  21215. this._singleClick = b;
  21216. },
  21217. enumerable: true,
  21218. configurable: true
  21219. });
  21220. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21221. get: function () {
  21222. return this._doubleClick;
  21223. },
  21224. set: function (b) {
  21225. this._doubleClick = b;
  21226. },
  21227. enumerable: true,
  21228. configurable: true
  21229. });
  21230. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21231. get: function () {
  21232. return this._hasSwiped;
  21233. },
  21234. set: function (b) {
  21235. this._hasSwiped = b;
  21236. },
  21237. enumerable: true,
  21238. configurable: true
  21239. });
  21240. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21241. get: function () {
  21242. return this._ignore;
  21243. },
  21244. set: function (b) {
  21245. this._ignore = b;
  21246. },
  21247. enumerable: true,
  21248. configurable: true
  21249. });
  21250. return ClickInfo;
  21251. }());
  21252. /**
  21253. * This class is used by the onRenderingGroupObservable
  21254. */
  21255. var RenderingGroupInfo = /** @class */ (function () {
  21256. function RenderingGroupInfo() {
  21257. }
  21258. /**
  21259. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21260. * This stage will be fired no matter what
  21261. */
  21262. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21263. /**
  21264. * Called before opaque object are rendered.
  21265. * This stage will be fired only if there's 3D Opaque content to render
  21266. */
  21267. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21268. /**
  21269. * Called after the opaque objects are rendered and before the transparent ones
  21270. * This stage will be fired only if there's 3D transparent content to render
  21271. */
  21272. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21273. /**
  21274. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21275. * This stage will be fired no matter what
  21276. */
  21277. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21278. return RenderingGroupInfo;
  21279. }());
  21280. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21281. /**
  21282. * Represents a scene to be rendered by the engine.
  21283. * @see http://doc.babylonjs.com/page.php?p=21911
  21284. */
  21285. var Scene = /** @class */ (function () {
  21286. /**
  21287. * @constructor
  21288. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21289. */
  21290. function Scene(engine) {
  21291. // Members
  21292. this.autoClear = true;
  21293. this.autoClearDepthAndStencil = true;
  21294. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21295. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21296. this.forceWireframe = false;
  21297. this._forcePointsCloud = false;
  21298. this.forceShowBoundingBoxes = false;
  21299. this.animationsEnabled = true;
  21300. this.useConstantAnimationDeltaTime = false;
  21301. this.constantlyUpdateMeshUnderPointer = false;
  21302. this.hoverCursor = "pointer";
  21303. this.defaultCursor = "";
  21304. /**
  21305. * This is used to call preventDefault() on pointer down
  21306. * in order to block unwanted artifacts like system double clicks
  21307. */
  21308. this.preventDefaultOnPointerDown = true;
  21309. // Metadata
  21310. this.metadata = null;
  21311. /**
  21312. * An event triggered when the scene is disposed.
  21313. * @type {BABYLON.Observable}
  21314. */
  21315. this.onDisposeObservable = new BABYLON.Observable();
  21316. /**
  21317. * An event triggered before rendering the scene (right after animations and physics)
  21318. * @type {BABYLON.Observable}
  21319. */
  21320. this.onBeforeRenderObservable = new BABYLON.Observable();
  21321. /**
  21322. * An event triggered after rendering the scene
  21323. * @type {BABYLON.Observable}
  21324. */
  21325. this.onAfterRenderObservable = new BABYLON.Observable();
  21326. /**
  21327. * An event triggered before animating the scene
  21328. * @type {BABYLON.Observable}
  21329. */
  21330. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21331. /**
  21332. * An event triggered after animations processing
  21333. * @type {BABYLON.Observable}
  21334. */
  21335. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21336. /**
  21337. * An event triggered before draw calls are ready to be sent
  21338. * @type {BABYLON.Observable}
  21339. */
  21340. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21341. /**
  21342. * An event triggered after draw calls have been sent
  21343. * @type {BABYLON.Observable}
  21344. */
  21345. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21346. /**
  21347. * An event triggered when physic simulation is about to be run
  21348. * @type {BABYLON.Observable}
  21349. */
  21350. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21351. /**
  21352. * An event triggered when physic simulation has been done
  21353. * @type {BABYLON.Observable}
  21354. */
  21355. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21356. /**
  21357. * An event triggered when the scene is ready
  21358. * @type {BABYLON.Observable}
  21359. */
  21360. this.onReadyObservable = new BABYLON.Observable();
  21361. /**
  21362. * An event triggered before rendering a camera
  21363. * @type {BABYLON.Observable}
  21364. */
  21365. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21366. /**
  21367. * An event triggered after rendering a camera
  21368. * @type {BABYLON.Observable}
  21369. */
  21370. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21371. /**
  21372. * An event triggered when active meshes evaluation is about to start
  21373. * @type {BABYLON.Observable}
  21374. */
  21375. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21376. /**
  21377. * An event triggered when active meshes evaluation is done
  21378. * @type {BABYLON.Observable}
  21379. */
  21380. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21381. /**
  21382. * An event triggered when particles rendering is about to start
  21383. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21384. * @type {BABYLON.Observable}
  21385. */
  21386. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21387. /**
  21388. * An event triggered when particles rendering is done
  21389. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21390. * @type {BABYLON.Observable}
  21391. */
  21392. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21393. /**
  21394. * An event triggered when sprites rendering is about to start
  21395. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21396. * @type {BABYLON.Observable}
  21397. */
  21398. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21399. /**
  21400. * An event triggered when sprites rendering is done
  21401. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21402. * @type {BABYLON.Observable}
  21403. */
  21404. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21405. /**
  21406. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21407. * @type {BABYLON.Observable}
  21408. */
  21409. this.onDataLoadedObservable = new BABYLON.Observable();
  21410. /**
  21411. * An event triggered when a camera is created
  21412. * @type {BABYLON.Observable}
  21413. */
  21414. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21415. /**
  21416. * An event triggered when a camera is removed
  21417. * @type {BABYLON.Observable}
  21418. */
  21419. this.onCameraRemovedObservable = new BABYLON.Observable();
  21420. /**
  21421. * An event triggered when a light is created
  21422. * @type {BABYLON.Observable}
  21423. */
  21424. this.onNewLightAddedObservable = new BABYLON.Observable();
  21425. /**
  21426. * An event triggered when a light is removed
  21427. * @type {BABYLON.Observable}
  21428. */
  21429. this.onLightRemovedObservable = new BABYLON.Observable();
  21430. /**
  21431. * An event triggered when a geometry is created
  21432. * @type {BABYLON.Observable}
  21433. */
  21434. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21435. /**
  21436. * An event triggered when a geometry is removed
  21437. * @type {BABYLON.Observable}
  21438. */
  21439. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21440. /**
  21441. * An event triggered when a transform node is created
  21442. * @type {BABYLON.Observable}
  21443. */
  21444. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21445. /**
  21446. * An event triggered when a transform node is removed
  21447. * @type {BABYLON.Observable}
  21448. */
  21449. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21450. /**
  21451. * An event triggered when a mesh is created
  21452. * @type {BABYLON.Observable}
  21453. */
  21454. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21455. /**
  21456. * An event triggered when a mesh is removed
  21457. * @type {BABYLON.Observable}
  21458. */
  21459. this.onMeshRemovedObservable = new BABYLON.Observable();
  21460. /**
  21461. * An event triggered when render targets are about to be rendered
  21462. * Can happen multiple times per frame.
  21463. * @type {BABYLON.Observable}
  21464. */
  21465. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21466. /**
  21467. * An event triggered when render targets were rendered.
  21468. * Can happen multiple times per frame.
  21469. * @type {BABYLON.Observable}
  21470. */
  21471. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21472. /**
  21473. * An event triggered before calculating deterministic simulation step
  21474. * @type {BABYLON.Observable}
  21475. */
  21476. this.onBeforeStepObservable = new BABYLON.Observable();
  21477. /**
  21478. * An event triggered after calculating deterministic simulation step
  21479. * @type {BABYLON.Observable}
  21480. */
  21481. this.onAfterStepObservable = new BABYLON.Observable();
  21482. /**
  21483. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21484. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21485. * 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)
  21486. */
  21487. this.onRenderingGroupObservable = new BABYLON.Observable();
  21488. // Animations
  21489. this.animations = [];
  21490. /**
  21491. * 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).
  21492. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21493. */
  21494. this.onPrePointerObservable = new BABYLON.Observable();
  21495. /**
  21496. * Observable event triggered each time an input event is received from the rendering canvas
  21497. */
  21498. this.onPointerObservable = new BABYLON.Observable();
  21499. this._meshPickProceed = false;
  21500. this._currentPickResult = null;
  21501. this._previousPickResult = null;
  21502. this._totalPointersPressed = 0;
  21503. this._doubleClickOccured = false;
  21504. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21505. this.cameraToUseForPointers = null;
  21506. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21507. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21508. this._startingPointerTime = 0;
  21509. this._previousStartingPointerTime = 0;
  21510. // Deterministic lockstep
  21511. this._timeAccumulator = 0;
  21512. this._currentStepId = 0;
  21513. this._currentInternalStep = 0;
  21514. // Keyboard
  21515. /**
  21516. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21517. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21518. */
  21519. this.onPreKeyboardObservable = new BABYLON.Observable();
  21520. /**
  21521. * Observable event triggered each time an keyboard event is received from the hosting window
  21522. */
  21523. this.onKeyboardObservable = new BABYLON.Observable();
  21524. // Coordinate system
  21525. /**
  21526. * use right-handed coordinate system on this scene.
  21527. * @type {boolean}
  21528. */
  21529. this._useRightHandedSystem = false;
  21530. // Fog
  21531. this._fogEnabled = true;
  21532. this._fogMode = Scene.FOGMODE_NONE;
  21533. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21534. this.fogDensity = 0.1;
  21535. this.fogStart = 0;
  21536. this.fogEnd = 1000.0;
  21537. // Lights
  21538. /**
  21539. * is shadow enabled on this scene.
  21540. * @type {boolean}
  21541. */
  21542. this._shadowsEnabled = true;
  21543. /**
  21544. * is light enabled on this scene.
  21545. * @type {boolean}
  21546. */
  21547. this._lightsEnabled = true;
  21548. /**
  21549. * All of the lights added to this scene.
  21550. * @see BABYLON.Light
  21551. * @type {BABYLON.Light[]}
  21552. */
  21553. this.lights = new Array();
  21554. // Cameras
  21555. /** All of the cameras added to this scene. */
  21556. this.cameras = new Array();
  21557. /** All of the active cameras added to this scene. */
  21558. this.activeCameras = new Array();
  21559. // Meshes
  21560. /**
  21561. * All of the tranform nodes added to this scene.
  21562. * @see BABYLON.TransformNode
  21563. * @type {BABYLON.TransformNode[]}
  21564. */
  21565. this.transformNodes = new Array();
  21566. /**
  21567. * All of the (abstract) meshes added to this scene.
  21568. * @see BABYLON.AbstractMesh
  21569. * @type {BABYLON.AbstractMesh[]}
  21570. */
  21571. this.meshes = new Array();
  21572. /**
  21573. * All of the animation groups added to this scene.
  21574. * @see BABYLON.AnimationGroup
  21575. * @type {BABYLON.AnimationGroup[]}
  21576. */
  21577. this.animationGroups = new Array();
  21578. // Geometries
  21579. this._geometries = new Array();
  21580. this.materials = new Array();
  21581. this.multiMaterials = new Array();
  21582. // Textures
  21583. this._texturesEnabled = true;
  21584. this.textures = new Array();
  21585. // Particles
  21586. this.particlesEnabled = true;
  21587. this.particleSystems = new Array();
  21588. // Sprites
  21589. this.spritesEnabled = true;
  21590. this.spriteManagers = new Array();
  21591. /**
  21592. * The list of layers (background and foreground) of the scene.
  21593. */
  21594. this.layers = new Array();
  21595. /**
  21596. * The list of effect layers (highlights/glow) contained in the scene.
  21597. */
  21598. this.effectLayers = new Array();
  21599. // Skeletons
  21600. this._skeletonsEnabled = true;
  21601. this.skeletons = new Array();
  21602. // Morph targets
  21603. this.morphTargetManagers = new Array();
  21604. // Lens flares
  21605. this.lensFlaresEnabled = true;
  21606. this.lensFlareSystems = new Array();
  21607. // Collisions
  21608. this.collisionsEnabled = true;
  21609. /** Defines the gravity applied to this scene */
  21610. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21611. // Postprocesses
  21612. this.postProcesses = new Array();
  21613. this.postProcessesEnabled = true;
  21614. // Customs render targets
  21615. this.renderTargetsEnabled = true;
  21616. this.dumpNextRenderTargets = false;
  21617. this.customRenderTargets = new Array();
  21618. // Imported meshes
  21619. this.importedMeshesFiles = new Array();
  21620. // Probes
  21621. this.probesEnabled = true;
  21622. this.reflectionProbes = new Array();
  21623. this._actionManagers = new Array();
  21624. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21625. // Procedural textures
  21626. this.proceduralTexturesEnabled = true;
  21627. this._proceduralTextures = new Array();
  21628. this.soundTracks = new Array();
  21629. this._audioEnabled = true;
  21630. this._headphone = false;
  21631. // Performance counters
  21632. this._totalVertices = new BABYLON.PerfCounter();
  21633. this._activeIndices = new BABYLON.PerfCounter();
  21634. this._activeParticles = new BABYLON.PerfCounter();
  21635. this._activeBones = new BABYLON.PerfCounter();
  21636. this._animationTime = 0;
  21637. this.animationTimeScale = 1;
  21638. this._renderId = 0;
  21639. this._executeWhenReadyTimeoutId = -1;
  21640. this._intermediateRendering = false;
  21641. this._viewUpdateFlag = -1;
  21642. this._projectionUpdateFlag = -1;
  21643. this._alternateViewUpdateFlag = -1;
  21644. this._alternateProjectionUpdateFlag = -1;
  21645. this._toBeDisposed = new BABYLON.SmartArray(256);
  21646. this._activeRequests = new Array();
  21647. this._pendingData = new Array();
  21648. this._isDisposed = false;
  21649. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21650. this._activeMeshes = new BABYLON.SmartArray(256);
  21651. this._processedMaterials = new BABYLON.SmartArray(256);
  21652. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21653. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21654. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21655. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21656. this._activeAnimatables = new Array();
  21657. this._transformMatrix = BABYLON.Matrix.Zero();
  21658. this._useAlternateCameraConfiguration = false;
  21659. this._alternateRendering = false;
  21660. this.requireLightSorting = false;
  21661. this._depthRenderer = {};
  21662. this._activeMeshesFrozen = false;
  21663. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21664. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21665. this._engine.scenes.push(this);
  21666. this._uid = null;
  21667. this._renderingManager = new BABYLON.RenderingManager(this);
  21668. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21669. if (BABYLON.OutlineRenderer) {
  21670. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21671. }
  21672. if (BABYLON.Tools.IsWindowObjectExist()) {
  21673. this.attachControl();
  21674. }
  21675. //simplification queue
  21676. if (BABYLON.SimplificationQueue) {
  21677. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21678. }
  21679. //collision coordinator initialization. For now legacy per default.
  21680. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21681. // Uniform Buffer
  21682. this._createUbo();
  21683. // Default Image processing definition.
  21684. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21685. }
  21686. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21687. /** The fog is deactivated */
  21688. get: function () {
  21689. return Scene._FOGMODE_NONE;
  21690. },
  21691. enumerable: true,
  21692. configurable: true
  21693. });
  21694. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21695. /** The fog density is following an exponential function */
  21696. get: function () {
  21697. return Scene._FOGMODE_EXP;
  21698. },
  21699. enumerable: true,
  21700. configurable: true
  21701. });
  21702. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21703. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21704. get: function () {
  21705. return Scene._FOGMODE_EXP2;
  21706. },
  21707. enumerable: true,
  21708. configurable: true
  21709. });
  21710. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21711. /** The fog density is following a linear function. */
  21712. get: function () {
  21713. return Scene._FOGMODE_LINEAR;
  21714. },
  21715. enumerable: true,
  21716. configurable: true
  21717. });
  21718. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21719. /**
  21720. * Texture used in all pbr material as the reflection texture.
  21721. * As in the majority of the scene they are the same (exception for multi room and so on),
  21722. * this is easier to reference from here than from all the materials.
  21723. */
  21724. get: function () {
  21725. return this._environmentTexture;
  21726. },
  21727. /**
  21728. * Texture used in all pbr material as the reflection texture.
  21729. * As in the majority of the scene they are the same (exception for multi room and so on),
  21730. * this is easier to set here than in all the materials.
  21731. */
  21732. set: function (value) {
  21733. if (this._environmentTexture === value) {
  21734. return;
  21735. }
  21736. this._environmentTexture = value;
  21737. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21738. },
  21739. enumerable: true,
  21740. configurable: true
  21741. });
  21742. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21743. /**
  21744. * Default image processing configuration used either in the rendering
  21745. * Forward main pass or through the imageProcessingPostProcess if present.
  21746. * As in the majority of the scene they are the same (exception for multi camera),
  21747. * this is easier to reference from here than from all the materials and post process.
  21748. *
  21749. * No setter as we it is a shared configuration, you can set the values instead.
  21750. */
  21751. get: function () {
  21752. return this._imageProcessingConfiguration;
  21753. },
  21754. enumerable: true,
  21755. configurable: true
  21756. });
  21757. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21758. get: function () {
  21759. return this._forcePointsCloud;
  21760. },
  21761. set: function (value) {
  21762. if (this._forcePointsCloud === value) {
  21763. return;
  21764. }
  21765. this._forcePointsCloud = value;
  21766. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21767. },
  21768. enumerable: true,
  21769. configurable: true
  21770. });
  21771. Object.defineProperty(Scene.prototype, "onDispose", {
  21772. /** A function to be executed when this scene is disposed. */
  21773. set: function (callback) {
  21774. if (this._onDisposeObserver) {
  21775. this.onDisposeObservable.remove(this._onDisposeObserver);
  21776. }
  21777. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21778. },
  21779. enumerable: true,
  21780. configurable: true
  21781. });
  21782. Object.defineProperty(Scene.prototype, "beforeRender", {
  21783. /** A function to be executed before rendering this scene */
  21784. set: function (callback) {
  21785. if (this._onBeforeRenderObserver) {
  21786. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21787. }
  21788. if (callback) {
  21789. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21790. }
  21791. },
  21792. enumerable: true,
  21793. configurable: true
  21794. });
  21795. Object.defineProperty(Scene.prototype, "afterRender", {
  21796. /** A function to be executed after rendering this scene */
  21797. set: function (callback) {
  21798. if (this._onAfterRenderObserver) {
  21799. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21800. }
  21801. if (callback) {
  21802. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21803. }
  21804. },
  21805. enumerable: true,
  21806. configurable: true
  21807. });
  21808. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21809. set: function (callback) {
  21810. if (this._onBeforeCameraRenderObserver) {
  21811. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21812. }
  21813. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21814. },
  21815. enumerable: true,
  21816. configurable: true
  21817. });
  21818. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21819. set: function (callback) {
  21820. if (this._onAfterCameraRenderObserver) {
  21821. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21822. }
  21823. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21824. },
  21825. enumerable: true,
  21826. configurable: true
  21827. });
  21828. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21829. get: function () {
  21830. if (!this._gamepadManager) {
  21831. this._gamepadManager = new BABYLON.GamepadManager(this);
  21832. }
  21833. return this._gamepadManager;
  21834. },
  21835. enumerable: true,
  21836. configurable: true
  21837. });
  21838. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21839. get: function () {
  21840. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21841. },
  21842. enumerable: true,
  21843. configurable: true
  21844. });
  21845. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21846. get: function () {
  21847. return this._useRightHandedSystem;
  21848. },
  21849. set: function (value) {
  21850. if (this._useRightHandedSystem === value) {
  21851. return;
  21852. }
  21853. this._useRightHandedSystem = value;
  21854. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21855. },
  21856. enumerable: true,
  21857. configurable: true
  21858. });
  21859. Scene.prototype.setStepId = function (newStepId) {
  21860. this._currentStepId = newStepId;
  21861. };
  21862. ;
  21863. Scene.prototype.getStepId = function () {
  21864. return this._currentStepId;
  21865. };
  21866. ;
  21867. Scene.prototype.getInternalStep = function () {
  21868. return this._currentInternalStep;
  21869. };
  21870. ;
  21871. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21872. get: function () {
  21873. return this._fogEnabled;
  21874. },
  21875. /**
  21876. * is fog enabled on this scene.
  21877. */
  21878. set: function (value) {
  21879. if (this._fogEnabled === value) {
  21880. return;
  21881. }
  21882. this._fogEnabled = value;
  21883. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21884. },
  21885. enumerable: true,
  21886. configurable: true
  21887. });
  21888. Object.defineProperty(Scene.prototype, "fogMode", {
  21889. get: function () {
  21890. return this._fogMode;
  21891. },
  21892. set: function (value) {
  21893. if (this._fogMode === value) {
  21894. return;
  21895. }
  21896. this._fogMode = value;
  21897. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21898. },
  21899. enumerable: true,
  21900. configurable: true
  21901. });
  21902. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21903. get: function () {
  21904. return this._shadowsEnabled;
  21905. },
  21906. set: function (value) {
  21907. if (this._shadowsEnabled === value) {
  21908. return;
  21909. }
  21910. this._shadowsEnabled = value;
  21911. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21912. },
  21913. enumerable: true,
  21914. configurable: true
  21915. });
  21916. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21917. get: function () {
  21918. return this._lightsEnabled;
  21919. },
  21920. set: function (value) {
  21921. if (this._lightsEnabled === value) {
  21922. return;
  21923. }
  21924. this._lightsEnabled = value;
  21925. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21926. },
  21927. enumerable: true,
  21928. configurable: true
  21929. });
  21930. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21931. /** The default material used on meshes when no material is affected */
  21932. get: function () {
  21933. if (!this._defaultMaterial) {
  21934. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21935. }
  21936. return this._defaultMaterial;
  21937. },
  21938. /** The default material used on meshes when no material is affected */
  21939. set: function (value) {
  21940. this._defaultMaterial = value;
  21941. },
  21942. enumerable: true,
  21943. configurable: true
  21944. });
  21945. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21946. get: function () {
  21947. return this._texturesEnabled;
  21948. },
  21949. set: function (value) {
  21950. if (this._texturesEnabled === value) {
  21951. return;
  21952. }
  21953. this._texturesEnabled = value;
  21954. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21955. },
  21956. enumerable: true,
  21957. configurable: true
  21958. });
  21959. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21960. get: function () {
  21961. return this._skeletonsEnabled;
  21962. },
  21963. set: function (value) {
  21964. if (this._skeletonsEnabled === value) {
  21965. return;
  21966. }
  21967. this._skeletonsEnabled = value;
  21968. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21969. },
  21970. enumerable: true,
  21971. configurable: true
  21972. });
  21973. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21974. get: function () {
  21975. if (!this._postProcessRenderPipelineManager) {
  21976. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21977. }
  21978. return this._postProcessRenderPipelineManager;
  21979. },
  21980. enumerable: true,
  21981. configurable: true
  21982. });
  21983. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21984. get: function () {
  21985. if (!this._mainSoundTrack) {
  21986. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21987. }
  21988. return this._mainSoundTrack;
  21989. },
  21990. enumerable: true,
  21991. configurable: true
  21992. });
  21993. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21994. get: function () {
  21995. return this._alternateRendering;
  21996. },
  21997. enumerable: true,
  21998. configurable: true
  21999. });
  22000. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22001. get: function () {
  22002. return this._frustumPlanes;
  22003. },
  22004. enumerable: true,
  22005. configurable: true
  22006. });
  22007. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22008. /**
  22009. * Gets the current geometry buffer associated to the scene.
  22010. */
  22011. get: function () {
  22012. return this._geometryBufferRenderer;
  22013. },
  22014. /**
  22015. * Sets the current geometry buffer for the scene.
  22016. */
  22017. set: function (geometryBufferRenderer) {
  22018. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22019. this._geometryBufferRenderer = geometryBufferRenderer;
  22020. }
  22021. },
  22022. enumerable: true,
  22023. configurable: true
  22024. });
  22025. Object.defineProperty(Scene.prototype, "debugLayer", {
  22026. // Properties
  22027. get: function () {
  22028. if (!this._debugLayer) {
  22029. this._debugLayer = new BABYLON.DebugLayer(this);
  22030. }
  22031. return this._debugLayer;
  22032. },
  22033. enumerable: true,
  22034. configurable: true
  22035. });
  22036. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22037. get: function () {
  22038. return this._workerCollisions;
  22039. },
  22040. set: function (enabled) {
  22041. if (!BABYLON.CollisionCoordinatorLegacy) {
  22042. return;
  22043. }
  22044. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22045. this._workerCollisions = enabled;
  22046. if (this.collisionCoordinator) {
  22047. this.collisionCoordinator.destroy();
  22048. }
  22049. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22050. this.collisionCoordinator.init(this);
  22051. },
  22052. enumerable: true,
  22053. configurable: true
  22054. });
  22055. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22056. get: function () {
  22057. return this._selectionOctree;
  22058. },
  22059. enumerable: true,
  22060. configurable: true
  22061. });
  22062. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22063. /**
  22064. * The mesh that is currently under the pointer.
  22065. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22066. */
  22067. get: function () {
  22068. return this._pointerOverMesh;
  22069. },
  22070. enumerable: true,
  22071. configurable: true
  22072. });
  22073. Object.defineProperty(Scene.prototype, "pointerX", {
  22074. /**
  22075. * Current on-screen X position of the pointer
  22076. * @return {number} X position of the pointer
  22077. */
  22078. get: function () {
  22079. return this._pointerX;
  22080. },
  22081. enumerable: true,
  22082. configurable: true
  22083. });
  22084. Object.defineProperty(Scene.prototype, "pointerY", {
  22085. /**
  22086. * Current on-screen Y position of the pointer
  22087. * @return {number} Y position of the pointer
  22088. */
  22089. get: function () {
  22090. return this._pointerY;
  22091. },
  22092. enumerable: true,
  22093. configurable: true
  22094. });
  22095. Scene.prototype.getCachedMaterial = function () {
  22096. return this._cachedMaterial;
  22097. };
  22098. Scene.prototype.getCachedEffect = function () {
  22099. return this._cachedEffect;
  22100. };
  22101. Scene.prototype.getCachedVisibility = function () {
  22102. return this._cachedVisibility;
  22103. };
  22104. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22105. if (visibility === void 0) { visibility = 1; }
  22106. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22107. };
  22108. Scene.prototype.getBoundingBoxRenderer = function () {
  22109. if (!this._boundingBoxRenderer) {
  22110. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22111. }
  22112. return this._boundingBoxRenderer;
  22113. };
  22114. Scene.prototype.getOutlineRenderer = function () {
  22115. return this._outlineRenderer;
  22116. };
  22117. Scene.prototype.getEngine = function () {
  22118. return this._engine;
  22119. };
  22120. Scene.prototype.getTotalVertices = function () {
  22121. return this._totalVertices.current;
  22122. };
  22123. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22124. get: function () {
  22125. return this._totalVertices;
  22126. },
  22127. enumerable: true,
  22128. configurable: true
  22129. });
  22130. Scene.prototype.getActiveIndices = function () {
  22131. return this._activeIndices.current;
  22132. };
  22133. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22134. get: function () {
  22135. return this._activeIndices;
  22136. },
  22137. enumerable: true,
  22138. configurable: true
  22139. });
  22140. Scene.prototype.getActiveParticles = function () {
  22141. return this._activeParticles.current;
  22142. };
  22143. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22144. get: function () {
  22145. return this._activeParticles;
  22146. },
  22147. enumerable: true,
  22148. configurable: true
  22149. });
  22150. Scene.prototype.getActiveBones = function () {
  22151. return this._activeBones.current;
  22152. };
  22153. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22154. get: function () {
  22155. return this._activeBones;
  22156. },
  22157. enumerable: true,
  22158. configurable: true
  22159. });
  22160. // Stats
  22161. Scene.prototype.getInterFramePerfCounter = function () {
  22162. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22163. return 0;
  22164. };
  22165. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22166. get: function () {
  22167. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22168. return null;
  22169. },
  22170. enumerable: true,
  22171. configurable: true
  22172. });
  22173. Scene.prototype.getLastFrameDuration = function () {
  22174. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22175. return 0;
  22176. };
  22177. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22178. get: function () {
  22179. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22180. return null;
  22181. },
  22182. enumerable: true,
  22183. configurable: true
  22184. });
  22185. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22186. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22187. return 0;
  22188. };
  22189. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22190. get: function () {
  22191. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22192. return null;
  22193. },
  22194. enumerable: true,
  22195. configurable: true
  22196. });
  22197. Scene.prototype.getActiveMeshes = function () {
  22198. return this._activeMeshes;
  22199. };
  22200. Scene.prototype.getRenderTargetsDuration = function () {
  22201. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22202. return 0;
  22203. };
  22204. Scene.prototype.getRenderDuration = function () {
  22205. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22206. return 0;
  22207. };
  22208. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22209. get: function () {
  22210. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22211. return null;
  22212. },
  22213. enumerable: true,
  22214. configurable: true
  22215. });
  22216. Scene.prototype.getParticlesDuration = function () {
  22217. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22218. return 0;
  22219. };
  22220. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22221. get: function () {
  22222. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22223. return null;
  22224. },
  22225. enumerable: true,
  22226. configurable: true
  22227. });
  22228. Scene.prototype.getSpritesDuration = function () {
  22229. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22230. return 0;
  22231. };
  22232. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22233. get: function () {
  22234. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22235. return null;
  22236. },
  22237. enumerable: true,
  22238. configurable: true
  22239. });
  22240. Scene.prototype.getAnimationRatio = function () {
  22241. return this._animationRatio;
  22242. };
  22243. Scene.prototype.getRenderId = function () {
  22244. return this._renderId;
  22245. };
  22246. Scene.prototype.incrementRenderId = function () {
  22247. this._renderId++;
  22248. };
  22249. Scene.prototype._updatePointerPosition = function (evt) {
  22250. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22251. if (!canvasRect) {
  22252. return;
  22253. }
  22254. this._pointerX = evt.clientX - canvasRect.left;
  22255. this._pointerY = evt.clientY - canvasRect.top;
  22256. this._unTranslatedPointerX = this._pointerX;
  22257. this._unTranslatedPointerY = this._pointerY;
  22258. };
  22259. Scene.prototype._createUbo = function () {
  22260. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22261. this._sceneUbo.addUniform("viewProjection", 16);
  22262. this._sceneUbo.addUniform("view", 16);
  22263. };
  22264. Scene.prototype._createAlternateUbo = function () {
  22265. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22266. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22267. this._alternateSceneUbo.addUniform("view", 16);
  22268. };
  22269. // Pointers handling
  22270. /**
  22271. * Use this method to simulate a pointer move on a mesh
  22272. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22273. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22274. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22275. */
  22276. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22277. var evt = new PointerEvent("pointermove", pointerEventInit);
  22278. return this._processPointerMove(pickResult, evt);
  22279. };
  22280. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22281. var canvas = this._engine.getRenderingCanvas();
  22282. if (!canvas) {
  22283. return this;
  22284. }
  22285. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22286. this.setPointerOverSprite(null);
  22287. this.setPointerOverMesh(pickResult.pickedMesh);
  22288. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22289. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22290. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22291. }
  22292. else {
  22293. canvas.style.cursor = this.hoverCursor;
  22294. }
  22295. }
  22296. else {
  22297. canvas.style.cursor = this.defaultCursor;
  22298. }
  22299. }
  22300. else {
  22301. this.setPointerOverMesh(null);
  22302. // Sprites
  22303. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22304. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22305. this.setPointerOverSprite(pickResult.pickedSprite);
  22306. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22307. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22308. }
  22309. else {
  22310. canvas.style.cursor = this.hoverCursor;
  22311. }
  22312. }
  22313. else {
  22314. this.setPointerOverSprite(null);
  22315. // Restore pointer
  22316. canvas.style.cursor = this.defaultCursor;
  22317. }
  22318. }
  22319. if (pickResult) {
  22320. if (this.onPointerMove) {
  22321. this.onPointerMove(evt, pickResult);
  22322. }
  22323. if (this.onPointerObservable.hasObservers()) {
  22324. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22325. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22326. this.onPointerObservable.notifyObservers(pi, type);
  22327. }
  22328. }
  22329. return this;
  22330. };
  22331. /**
  22332. * Use this method to simulate a pointer down on a mesh
  22333. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22334. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22335. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22336. */
  22337. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22338. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22339. return this._processPointerDown(pickResult, evt);
  22340. };
  22341. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22342. var _this = this;
  22343. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22344. this._pickedDownMesh = pickResult.pickedMesh;
  22345. var actionManager = pickResult.pickedMesh.actionManager;
  22346. if (actionManager) {
  22347. if (actionManager.hasPickTriggers) {
  22348. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22349. switch (evt.button) {
  22350. case 0:
  22351. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22352. break;
  22353. case 1:
  22354. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22355. break;
  22356. case 2:
  22357. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22358. break;
  22359. }
  22360. }
  22361. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22362. window.setTimeout(function () {
  22363. 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);
  22364. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22365. if (_this._totalPointersPressed !== 0 &&
  22366. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22367. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22368. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22369. _this._startingPointerTime = 0;
  22370. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22371. }
  22372. }
  22373. }, Scene.LongPressDelay);
  22374. }
  22375. }
  22376. }
  22377. if (pickResult) {
  22378. if (this.onPointerDown) {
  22379. this.onPointerDown(evt, pickResult);
  22380. }
  22381. if (this.onPointerObservable.hasObservers()) {
  22382. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22383. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22384. this.onPointerObservable.notifyObservers(pi, type);
  22385. }
  22386. }
  22387. return this;
  22388. };
  22389. /**
  22390. * Use this method to simulate a pointer up on a mesh
  22391. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22392. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22393. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22394. */
  22395. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22396. var evt = new PointerEvent("pointerup", pointerEventInit);
  22397. var clickInfo = new ClickInfo();
  22398. clickInfo.singleClick = true;
  22399. clickInfo.ignore = true;
  22400. return this._processPointerUp(pickResult, evt, clickInfo);
  22401. };
  22402. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22403. if (pickResult && pickResult && pickResult.pickedMesh) {
  22404. this._pickedUpMesh = pickResult.pickedMesh;
  22405. if (this._pickedDownMesh === this._pickedUpMesh) {
  22406. if (this.onPointerPick) {
  22407. this.onPointerPick(evt, pickResult);
  22408. }
  22409. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22410. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22411. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22412. this.onPointerObservable.notifyObservers(pi, type);
  22413. }
  22414. }
  22415. if (pickResult.pickedMesh.actionManager) {
  22416. if (clickInfo.ignore) {
  22417. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22418. }
  22419. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22420. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22421. }
  22422. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22423. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22424. }
  22425. }
  22426. }
  22427. if (this._pickedDownMesh &&
  22428. this._pickedDownMesh.actionManager &&
  22429. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22430. this._pickedDownMesh !== this._pickedUpMesh) {
  22431. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22432. }
  22433. if (this.onPointerUp) {
  22434. this.onPointerUp(evt, pickResult);
  22435. }
  22436. if (this.onPointerObservable.hasObservers()) {
  22437. if (!clickInfo.ignore) {
  22438. if (!clickInfo.hasSwiped) {
  22439. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22440. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22441. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22442. this.onPointerObservable.notifyObservers(pi, type);
  22443. }
  22444. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22445. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22446. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22447. this.onPointerObservable.notifyObservers(pi, type);
  22448. }
  22449. }
  22450. }
  22451. else {
  22452. var type = BABYLON.PointerEventTypes.POINTERUP;
  22453. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22454. this.onPointerObservable.notifyObservers(pi, type);
  22455. }
  22456. }
  22457. return this;
  22458. };
  22459. /**
  22460. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22461. * @param attachUp defines if you want to attach events to pointerup
  22462. * @param attachDown defines if you want to attach events to pointerdown
  22463. * @param attachMove defines if you want to attach events to pointermove
  22464. */
  22465. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22466. var _this = this;
  22467. if (attachUp === void 0) { attachUp = true; }
  22468. if (attachDown === void 0) { attachDown = true; }
  22469. if (attachMove === void 0) { attachMove = true; }
  22470. this._initActionManager = function (act, clickInfo) {
  22471. if (!_this._meshPickProceed) {
  22472. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22473. _this._currentPickResult = pickResult;
  22474. if (pickResult) {
  22475. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22476. }
  22477. _this._meshPickProceed = true;
  22478. }
  22479. return act;
  22480. };
  22481. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22482. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22483. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22484. btn !== _this._previousButtonPressed) {
  22485. _this._doubleClickOccured = false;
  22486. clickInfo.singleClick = true;
  22487. clickInfo.ignore = false;
  22488. cb(clickInfo, _this._currentPickResult);
  22489. }
  22490. };
  22491. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22492. var clickInfo = new ClickInfo();
  22493. _this._currentPickResult = null;
  22494. var act = null;
  22495. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22496. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22497. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22498. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22499. act = _this._initActionManager(act, clickInfo);
  22500. if (act)
  22501. checkPicking = act.hasPickTriggers;
  22502. }
  22503. if (checkPicking) {
  22504. var btn = evt.button;
  22505. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22506. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22507. if (!clickInfo.hasSwiped) {
  22508. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22509. if (!checkSingleClickImmediately) {
  22510. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22511. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22512. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22513. act = _this._initActionManager(act, clickInfo);
  22514. if (act)
  22515. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22516. }
  22517. }
  22518. if (checkSingleClickImmediately) {
  22519. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22520. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22521. btn !== _this._previousButtonPressed) {
  22522. clickInfo.singleClick = true;
  22523. cb(clickInfo, _this._currentPickResult);
  22524. }
  22525. }
  22526. else {
  22527. // wait that no double click has been raised during the double click delay
  22528. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22529. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22530. }
  22531. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22532. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22533. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22534. act = _this._initActionManager(act, clickInfo);
  22535. if (act)
  22536. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22537. }
  22538. if (checkDoubleClick) {
  22539. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22540. if (btn === _this._previousButtonPressed &&
  22541. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22542. !_this._doubleClickOccured) {
  22543. // pointer has not moved for 2 clicks, it's a double click
  22544. if (!clickInfo.hasSwiped &&
  22545. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22546. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22547. _this._previousStartingPointerTime = 0;
  22548. _this._doubleClickOccured = true;
  22549. clickInfo.doubleClick = true;
  22550. clickInfo.ignore = false;
  22551. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22552. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22553. }
  22554. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22555. cb(clickInfo, _this._currentPickResult);
  22556. }
  22557. else {
  22558. _this._doubleClickOccured = false;
  22559. _this._previousStartingPointerTime = _this._startingPointerTime;
  22560. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22561. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22562. _this._previousButtonPressed = btn;
  22563. if (Scene.ExclusiveDoubleClickMode) {
  22564. if (_this._previousDelayedSimpleClickTimeout) {
  22565. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22566. }
  22567. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22568. cb(clickInfo, _this._previousPickResult);
  22569. }
  22570. else {
  22571. cb(clickInfo, _this._currentPickResult);
  22572. }
  22573. }
  22574. }
  22575. else {
  22576. _this._doubleClickOccured = false;
  22577. _this._previousStartingPointerTime = _this._startingPointerTime;
  22578. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22579. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22580. _this._previousButtonPressed = btn;
  22581. }
  22582. }
  22583. }
  22584. }
  22585. clickInfo.ignore = true;
  22586. cb(clickInfo, _this._currentPickResult);
  22587. };
  22588. this._spritePredicate = function (sprite) {
  22589. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22590. };
  22591. this._onPointerMove = function (evt) {
  22592. _this._updatePointerPosition(evt);
  22593. // PreObservable support
  22594. if (_this.onPrePointerObservable.hasObservers()) {
  22595. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22596. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22597. _this.onPrePointerObservable.notifyObservers(pi, type);
  22598. if (pi.skipOnPointerObservable) {
  22599. return;
  22600. }
  22601. }
  22602. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22603. return;
  22604. }
  22605. if (!_this.pointerMovePredicate) {
  22606. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22607. }
  22608. // Meshes
  22609. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22610. _this._processPointerMove(pickResult, evt);
  22611. };
  22612. this._onPointerDown = function (evt) {
  22613. _this._totalPointersPressed++;
  22614. _this._pickedDownMesh = null;
  22615. _this._meshPickProceed = false;
  22616. _this._updatePointerPosition(evt);
  22617. if (_this.preventDefaultOnPointerDown && canvas) {
  22618. evt.preventDefault();
  22619. canvas.focus();
  22620. }
  22621. // PreObservable support
  22622. if (_this.onPrePointerObservable.hasObservers()) {
  22623. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22624. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22625. _this.onPrePointerObservable.notifyObservers(pi, type);
  22626. if (pi.skipOnPointerObservable) {
  22627. return;
  22628. }
  22629. }
  22630. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22631. return;
  22632. }
  22633. _this._startingPointerPosition.x = _this._pointerX;
  22634. _this._startingPointerPosition.y = _this._pointerY;
  22635. _this._startingPointerTime = new Date().getTime();
  22636. if (!_this.pointerDownPredicate) {
  22637. _this.pointerDownPredicate = function (mesh) {
  22638. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22639. };
  22640. }
  22641. // Meshes
  22642. _this._pickedDownMesh = null;
  22643. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22644. _this._processPointerDown(pickResult, evt);
  22645. // Sprites
  22646. _this._pickedDownSprite = null;
  22647. if (_this.spriteManagers.length > 0) {
  22648. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22649. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22650. if (pickResult.pickedSprite.actionManager) {
  22651. _this._pickedDownSprite = pickResult.pickedSprite;
  22652. switch (evt.button) {
  22653. case 0:
  22654. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22655. break;
  22656. case 1:
  22657. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22658. break;
  22659. case 2:
  22660. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22661. break;
  22662. }
  22663. if (pickResult.pickedSprite.actionManager) {
  22664. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22665. }
  22666. }
  22667. }
  22668. }
  22669. };
  22670. this._onPointerUp = function (evt) {
  22671. if (_this._totalPointersPressed === 0) {
  22672. return; // So we need to test it the pointer down was pressed before.
  22673. }
  22674. _this._totalPointersPressed--;
  22675. _this._pickedUpMesh = null;
  22676. _this._meshPickProceed = false;
  22677. _this._updatePointerPosition(evt);
  22678. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22679. // PreObservable support
  22680. if (_this.onPrePointerObservable.hasObservers()) {
  22681. if (!clickInfo.ignore) {
  22682. if (!clickInfo.hasSwiped) {
  22683. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22684. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22685. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22686. _this.onPrePointerObservable.notifyObservers(pi, type);
  22687. if (pi.skipOnPointerObservable) {
  22688. return;
  22689. }
  22690. }
  22691. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22692. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22693. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22694. _this.onPrePointerObservable.notifyObservers(pi, type);
  22695. if (pi.skipOnPointerObservable) {
  22696. return;
  22697. }
  22698. }
  22699. }
  22700. }
  22701. else {
  22702. var type = BABYLON.PointerEventTypes.POINTERUP;
  22703. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22704. _this.onPrePointerObservable.notifyObservers(pi, type);
  22705. if (pi.skipOnPointerObservable) {
  22706. return;
  22707. }
  22708. }
  22709. }
  22710. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22711. return;
  22712. }
  22713. if (!_this.pointerUpPredicate) {
  22714. _this.pointerUpPredicate = function (mesh) {
  22715. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22716. };
  22717. }
  22718. // Meshes
  22719. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22720. _this._initActionManager(null, clickInfo);
  22721. }
  22722. if (!pickResult) {
  22723. pickResult = _this._currentPickResult;
  22724. }
  22725. _this._processPointerUp(pickResult, evt, clickInfo);
  22726. // Sprites
  22727. if (_this.spriteManagers.length > 0) {
  22728. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22729. if (spritePickResult) {
  22730. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22731. if (spritePickResult.pickedSprite.actionManager) {
  22732. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22733. if (spritePickResult.pickedSprite.actionManager) {
  22734. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22735. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22736. }
  22737. }
  22738. }
  22739. }
  22740. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22741. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22742. }
  22743. }
  22744. }
  22745. _this._previousPickResult = _this._currentPickResult;
  22746. });
  22747. };
  22748. this._onKeyDown = function (evt) {
  22749. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22750. if (_this.onPreKeyboardObservable.hasObservers()) {
  22751. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22752. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22753. if (pi.skipOnPointerObservable) {
  22754. return;
  22755. }
  22756. }
  22757. if (_this.onKeyboardObservable.hasObservers()) {
  22758. var pi = new BABYLON.KeyboardInfo(type, evt);
  22759. _this.onKeyboardObservable.notifyObservers(pi, type);
  22760. }
  22761. if (_this.actionManager) {
  22762. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22763. }
  22764. };
  22765. this._onKeyUp = function (evt) {
  22766. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22767. if (_this.onPreKeyboardObservable.hasObservers()) {
  22768. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22769. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22770. if (pi.skipOnPointerObservable) {
  22771. return;
  22772. }
  22773. }
  22774. if (_this.onKeyboardObservable.hasObservers()) {
  22775. var pi = new BABYLON.KeyboardInfo(type, evt);
  22776. _this.onKeyboardObservable.notifyObservers(pi, type);
  22777. }
  22778. if (_this.actionManager) {
  22779. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22780. }
  22781. };
  22782. var engine = this.getEngine();
  22783. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22784. if (!canvas) {
  22785. return;
  22786. }
  22787. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22788. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22789. });
  22790. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22791. if (!canvas) {
  22792. return;
  22793. }
  22794. canvas.removeEventListener("keydown", _this._onKeyDown);
  22795. canvas.removeEventListener("keyup", _this._onKeyUp);
  22796. });
  22797. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22798. var canvas = this._engine.getRenderingCanvas();
  22799. if (!canvas) {
  22800. return;
  22801. }
  22802. if (attachMove) {
  22803. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22804. // Wheel
  22805. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22806. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22807. }
  22808. if (attachDown) {
  22809. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22810. }
  22811. if (attachUp) {
  22812. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22813. }
  22814. canvas.tabIndex = 1;
  22815. };
  22816. Scene.prototype.detachControl = function () {
  22817. var engine = this.getEngine();
  22818. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22819. var canvas = engine.getRenderingCanvas();
  22820. if (!canvas) {
  22821. return;
  22822. }
  22823. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22824. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22825. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22826. if (this._onCanvasBlurObserver) {
  22827. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22828. }
  22829. if (this._onCanvasFocusObserver) {
  22830. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22831. }
  22832. // Wheel
  22833. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22834. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22835. // Keyboard
  22836. canvas.removeEventListener("keydown", this._onKeyDown);
  22837. canvas.removeEventListener("keyup", this._onKeyUp);
  22838. // Observables
  22839. this.onKeyboardObservable.clear();
  22840. this.onPreKeyboardObservable.clear();
  22841. this.onPointerObservable.clear();
  22842. this.onPrePointerObservable.clear();
  22843. };
  22844. /**
  22845. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22846. * Delay loaded resources are not taking in account
  22847. * @return true if all required resources are ready
  22848. */
  22849. Scene.prototype.isReady = function () {
  22850. if (this._isDisposed) {
  22851. return false;
  22852. }
  22853. if (this._pendingData.length > 0) {
  22854. return false;
  22855. }
  22856. var index;
  22857. var engine = this.getEngine();
  22858. // Geometries
  22859. for (index = 0; index < this._geometries.length; index++) {
  22860. var geometry = this._geometries[index];
  22861. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22862. return false;
  22863. }
  22864. }
  22865. // Meshes
  22866. for (index = 0; index < this.meshes.length; index++) {
  22867. var mesh = this.meshes[index];
  22868. if (!mesh.isEnabled()) {
  22869. continue;
  22870. }
  22871. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22872. continue;
  22873. }
  22874. if (!mesh.isReady(true)) {
  22875. return false;
  22876. }
  22877. // Effect layers
  22878. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22879. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22880. var layer = _a[_i];
  22881. if (!layer.hasMesh(mesh)) {
  22882. continue;
  22883. }
  22884. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22885. var subMesh = _c[_b];
  22886. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22887. return false;
  22888. }
  22889. }
  22890. }
  22891. }
  22892. return true;
  22893. };
  22894. Scene.prototype.resetCachedMaterial = function () {
  22895. this._cachedMaterial = null;
  22896. this._cachedEffect = null;
  22897. this._cachedVisibility = null;
  22898. };
  22899. Scene.prototype.registerBeforeRender = function (func) {
  22900. this.onBeforeRenderObservable.add(func);
  22901. };
  22902. Scene.prototype.unregisterBeforeRender = function (func) {
  22903. this.onBeforeRenderObservable.removeCallback(func);
  22904. };
  22905. Scene.prototype.registerAfterRender = function (func) {
  22906. this.onAfterRenderObservable.add(func);
  22907. };
  22908. Scene.prototype.unregisterAfterRender = function (func) {
  22909. this.onAfterRenderObservable.removeCallback(func);
  22910. };
  22911. Scene.prototype._executeOnceBeforeRender = function (func) {
  22912. var _this = this;
  22913. var execFunc = function () {
  22914. func();
  22915. setTimeout(function () {
  22916. _this.unregisterBeforeRender(execFunc);
  22917. });
  22918. };
  22919. this.registerBeforeRender(execFunc);
  22920. };
  22921. /**
  22922. * The provided function will run before render once and will be disposed afterwards.
  22923. * A timeout delay can be provided so that the function will be executed in N ms.
  22924. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22925. * @param func The function to be executed.
  22926. * @param timeout optional delay in ms
  22927. */
  22928. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22929. var _this = this;
  22930. if (timeout !== undefined) {
  22931. setTimeout(function () {
  22932. _this._executeOnceBeforeRender(func);
  22933. }, timeout);
  22934. }
  22935. else {
  22936. this._executeOnceBeforeRender(func);
  22937. }
  22938. };
  22939. Scene.prototype._addPendingData = function (data) {
  22940. this._pendingData.push(data);
  22941. };
  22942. Scene.prototype._removePendingData = function (data) {
  22943. var wasLoading = this.isLoading;
  22944. var index = this._pendingData.indexOf(data);
  22945. if (index !== -1) {
  22946. this._pendingData.splice(index, 1);
  22947. }
  22948. if (wasLoading && !this.isLoading) {
  22949. this.onDataLoadedObservable.notifyObservers(this);
  22950. }
  22951. };
  22952. Scene.prototype.getWaitingItemsCount = function () {
  22953. return this._pendingData.length;
  22954. };
  22955. Object.defineProperty(Scene.prototype, "isLoading", {
  22956. get: function () {
  22957. return this._pendingData.length > 0;
  22958. },
  22959. enumerable: true,
  22960. configurable: true
  22961. });
  22962. /**
  22963. * Registers a function to be executed when the scene is ready.
  22964. * @param {Function} func - the function to be executed.
  22965. */
  22966. Scene.prototype.executeWhenReady = function (func) {
  22967. var _this = this;
  22968. this.onReadyObservable.add(func);
  22969. if (this._executeWhenReadyTimeoutId !== -1) {
  22970. return;
  22971. }
  22972. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22973. _this._checkIsReady();
  22974. }, 150);
  22975. };
  22976. /**
  22977. * Returns a promise that resolves when the scene is ready.
  22978. * @returns A promise that resolves when the scene is ready.
  22979. */
  22980. Scene.prototype.whenReadyAsync = function () {
  22981. var _this = this;
  22982. return new Promise(function (resolve) {
  22983. _this.executeWhenReady(function () {
  22984. resolve();
  22985. });
  22986. });
  22987. };
  22988. Scene.prototype._checkIsReady = function () {
  22989. var _this = this;
  22990. if (this.isReady()) {
  22991. this.onReadyObservable.notifyObservers(this);
  22992. this.onReadyObservable.clear();
  22993. this._executeWhenReadyTimeoutId = -1;
  22994. return;
  22995. }
  22996. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22997. _this._checkIsReady();
  22998. }, 150);
  22999. };
  23000. // Animations
  23001. /**
  23002. * Will start the animation sequence of a given target
  23003. * @param target - the target
  23004. * @param {number} from - from which frame should animation start
  23005. * @param {number} to - till which frame should animation run.
  23006. * @param {boolean} [loop] - should the animation loop
  23007. * @param {number} [speedRatio] - the speed in which to run the animation
  23008. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  23009. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  23010. * Returns {BABYLON.Animatable} the animatable object created for this animation
  23011. * See BABYLON.Animatable
  23012. */
  23013. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  23014. if (speedRatio === void 0) { speedRatio = 1.0; }
  23015. if (from > to && speedRatio > 0) {
  23016. speedRatio *= -1;
  23017. }
  23018. this.stopAnimation(target);
  23019. if (!animatable) {
  23020. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23021. }
  23022. // Local animations
  23023. if (target.animations) {
  23024. animatable.appendAnimations(target, target.animations);
  23025. }
  23026. // Children animations
  23027. if (target.getAnimatables) {
  23028. var animatables = target.getAnimatables();
  23029. for (var index = 0; index < animatables.length; index++) {
  23030. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  23031. }
  23032. }
  23033. animatable.reset();
  23034. return animatable;
  23035. };
  23036. /**
  23037. * Begin a new animation on a given node
  23038. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23039. * @param {BABYLON.Animation[]} defines the list of animations to start
  23040. * @param {number} from defines the initial value
  23041. * @param {number} to defines the final value
  23042. * @param {boolean} loop defines if you want animation to loop (off by default)
  23043. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23044. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23045. * @returns the list of created animatables
  23046. */
  23047. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23048. if (speedRatio === undefined) {
  23049. speedRatio = 1.0;
  23050. }
  23051. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23052. return animatable;
  23053. };
  23054. /**
  23055. * Begin a new animation on a given node and its hierarchy
  23056. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23057. * @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.
  23058. * @param {BABYLON.Animation[]} defines the list of animations to start
  23059. * @param {number} from defines the initial value
  23060. * @param {number} to defines the final value
  23061. * @param {boolean} loop defines if you want animation to loop (off by default)
  23062. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23063. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23064. * @returns the list of animatables created for all nodes
  23065. */
  23066. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23067. var children = target.getDescendants(directDescendantsOnly);
  23068. var result = [];
  23069. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23070. var child = children_1[_i];
  23071. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23072. }
  23073. return result;
  23074. };
  23075. Scene.prototype.getAnimatableByTarget = function (target) {
  23076. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23077. if (this._activeAnimatables[index].target === target) {
  23078. return this._activeAnimatables[index];
  23079. }
  23080. }
  23081. return null;
  23082. };
  23083. Object.defineProperty(Scene.prototype, "animatables", {
  23084. get: function () {
  23085. return this._activeAnimatables;
  23086. },
  23087. enumerable: true,
  23088. configurable: true
  23089. });
  23090. /**
  23091. * Will stop the animation of the given target
  23092. * @param target - the target
  23093. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23094. * @see beginAnimation
  23095. */
  23096. Scene.prototype.stopAnimation = function (target, animationName) {
  23097. var animatable = this.getAnimatableByTarget(target);
  23098. if (animatable) {
  23099. animatable.stop(animationName);
  23100. }
  23101. };
  23102. /**
  23103. * Stops and removes all animations that have been applied to the scene
  23104. */
  23105. Scene.prototype.stopAllAnimations = function () {
  23106. if (this._activeAnimatables) {
  23107. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23108. this._activeAnimatables[i].stop();
  23109. }
  23110. this._activeAnimatables = [];
  23111. }
  23112. };
  23113. Scene.prototype._animate = function () {
  23114. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23115. return;
  23116. }
  23117. // Getting time
  23118. var now = BABYLON.Tools.Now;
  23119. if (!this._animationTimeLast) {
  23120. if (this._pendingData.length > 0) {
  23121. return;
  23122. }
  23123. this._animationTimeLast = now;
  23124. }
  23125. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23126. this._animationTime += deltaTime;
  23127. this._animationTimeLast = now;
  23128. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23129. this._activeAnimatables[index]._animate(this._animationTime);
  23130. }
  23131. };
  23132. // Matrix
  23133. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23134. this._useAlternateCameraConfiguration = active;
  23135. };
  23136. Scene.prototype.getViewMatrix = function () {
  23137. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23138. };
  23139. Scene.prototype.getProjectionMatrix = function () {
  23140. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23141. };
  23142. Scene.prototype.getTransformMatrix = function () {
  23143. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23144. };
  23145. Scene.prototype.setTransformMatrix = function (view, projection) {
  23146. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23147. return;
  23148. }
  23149. this._viewUpdateFlag = view.updateFlag;
  23150. this._projectionUpdateFlag = projection.updateFlag;
  23151. this._viewMatrix = view;
  23152. this._projectionMatrix = projection;
  23153. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23154. // Update frustum
  23155. if (!this._frustumPlanes) {
  23156. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23157. }
  23158. else {
  23159. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23160. }
  23161. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23162. var otherCamera = this.activeCamera._alternateCamera;
  23163. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23164. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23165. }
  23166. if (this._sceneUbo.useUbo) {
  23167. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23168. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23169. this._sceneUbo.update();
  23170. }
  23171. };
  23172. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23173. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23174. return;
  23175. }
  23176. this._alternateViewUpdateFlag = view.updateFlag;
  23177. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23178. this._alternateViewMatrix = view;
  23179. this._alternateProjectionMatrix = projection;
  23180. if (!this._alternateTransformMatrix) {
  23181. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23182. }
  23183. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23184. if (!this._alternateSceneUbo) {
  23185. this._createAlternateUbo();
  23186. }
  23187. if (this._alternateSceneUbo.useUbo) {
  23188. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23189. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23190. this._alternateSceneUbo.update();
  23191. }
  23192. };
  23193. Scene.prototype.getSceneUniformBuffer = function () {
  23194. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23195. };
  23196. // Methods
  23197. Scene.prototype.getUniqueId = function () {
  23198. var result = Scene._uniqueIdCounter;
  23199. Scene._uniqueIdCounter++;
  23200. return result;
  23201. };
  23202. Scene.prototype.addMesh = function (newMesh) {
  23203. this.meshes.push(newMesh);
  23204. //notify the collision coordinator
  23205. if (this.collisionCoordinator) {
  23206. this.collisionCoordinator.onMeshAdded(newMesh);
  23207. }
  23208. newMesh._resyncLightSources();
  23209. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23210. };
  23211. Scene.prototype.removeMesh = function (toRemove) {
  23212. var index = this.meshes.indexOf(toRemove);
  23213. if (index !== -1) {
  23214. // Remove from the scene if mesh found
  23215. this.meshes.splice(index, 1);
  23216. }
  23217. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23218. return index;
  23219. };
  23220. Scene.prototype.addTransformNode = function (newTransformNode) {
  23221. this.transformNodes.push(newTransformNode);
  23222. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23223. };
  23224. Scene.prototype.removeTransformNode = function (toRemove) {
  23225. var index = this.transformNodes.indexOf(toRemove);
  23226. if (index !== -1) {
  23227. // Remove from the scene if found
  23228. this.transformNodes.splice(index, 1);
  23229. }
  23230. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23231. return index;
  23232. };
  23233. Scene.prototype.removeSkeleton = function (toRemove) {
  23234. var index = this.skeletons.indexOf(toRemove);
  23235. if (index !== -1) {
  23236. // Remove from the scene if found
  23237. this.skeletons.splice(index, 1);
  23238. }
  23239. return index;
  23240. };
  23241. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23242. var index = this.morphTargetManagers.indexOf(toRemove);
  23243. if (index !== -1) {
  23244. // Remove from the scene if found
  23245. this.morphTargetManagers.splice(index, 1);
  23246. }
  23247. return index;
  23248. };
  23249. Scene.prototype.removeLight = function (toRemove) {
  23250. var index = this.lights.indexOf(toRemove);
  23251. if (index !== -1) {
  23252. // Remove from meshes
  23253. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23254. var mesh = _a[_i];
  23255. mesh._removeLightSource(toRemove);
  23256. }
  23257. // Remove from the scene if mesh found
  23258. this.lights.splice(index, 1);
  23259. this.sortLightsByPriority();
  23260. }
  23261. this.onLightRemovedObservable.notifyObservers(toRemove);
  23262. return index;
  23263. };
  23264. Scene.prototype.removeCamera = function (toRemove) {
  23265. var index = this.cameras.indexOf(toRemove);
  23266. if (index !== -1) {
  23267. // Remove from the scene if mesh found
  23268. this.cameras.splice(index, 1);
  23269. }
  23270. // Remove from activeCameras
  23271. var index2 = this.activeCameras.indexOf(toRemove);
  23272. if (index2 !== -1) {
  23273. // Remove from the scene if mesh found
  23274. this.activeCameras.splice(index2, 1);
  23275. }
  23276. // Reset the activeCamera
  23277. if (this.activeCamera === toRemove) {
  23278. if (this.cameras.length > 0) {
  23279. this.activeCamera = this.cameras[0];
  23280. }
  23281. else {
  23282. this.activeCamera = null;
  23283. }
  23284. }
  23285. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23286. return index;
  23287. };
  23288. Scene.prototype.removeParticleSystem = function (toRemove) {
  23289. var index = this.particleSystems.indexOf(toRemove);
  23290. if (index !== -1) {
  23291. this.particleSystems.splice(index, 1);
  23292. }
  23293. return index;
  23294. };
  23295. ;
  23296. Scene.prototype.removeAnimation = function (toRemove) {
  23297. var index = this.animations.indexOf(toRemove);
  23298. if (index !== -1) {
  23299. this.animations.splice(index, 1);
  23300. }
  23301. return index;
  23302. };
  23303. ;
  23304. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23305. var index = this.multiMaterials.indexOf(toRemove);
  23306. if (index !== -1) {
  23307. this.multiMaterials.splice(index, 1);
  23308. }
  23309. return index;
  23310. };
  23311. ;
  23312. Scene.prototype.removeMaterial = function (toRemove) {
  23313. var index = this.materials.indexOf(toRemove);
  23314. if (index !== -1) {
  23315. this.materials.splice(index, 1);
  23316. }
  23317. return index;
  23318. };
  23319. ;
  23320. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23321. var index = this.lensFlareSystems.indexOf(toRemove);
  23322. if (index !== -1) {
  23323. this.lensFlareSystems.splice(index, 1);
  23324. }
  23325. return index;
  23326. };
  23327. ;
  23328. Scene.prototype.removeActionManager = function (toRemove) {
  23329. var index = this._actionManagers.indexOf(toRemove);
  23330. if (index !== -1) {
  23331. this._actionManagers.splice(index, 1);
  23332. }
  23333. return index;
  23334. };
  23335. ;
  23336. Scene.prototype.addLight = function (newLight) {
  23337. this.lights.push(newLight);
  23338. this.sortLightsByPriority();
  23339. // Add light to all meshes (To support if the light is removed and then readded)
  23340. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23341. var mesh = _a[_i];
  23342. if (mesh._lightSources.indexOf(newLight) === -1) {
  23343. mesh._lightSources.push(newLight);
  23344. mesh._resyncLightSources();
  23345. }
  23346. }
  23347. this.onNewLightAddedObservable.notifyObservers(newLight);
  23348. };
  23349. Scene.prototype.sortLightsByPriority = function () {
  23350. if (this.requireLightSorting) {
  23351. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23352. }
  23353. };
  23354. Scene.prototype.addCamera = function (newCamera) {
  23355. this.cameras.push(newCamera);
  23356. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23357. };
  23358. Scene.prototype.addSkeleton = function (newSkeleton) {
  23359. this.skeletons.push(newSkeleton);
  23360. };
  23361. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23362. this.particleSystems.push(newParticleSystem);
  23363. };
  23364. Scene.prototype.addAnimation = function (newAnimation) {
  23365. this.animations.push(newAnimation);
  23366. };
  23367. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23368. this.multiMaterials.push(newMultiMaterial);
  23369. };
  23370. Scene.prototype.addMaterial = function (newMaterial) {
  23371. this.materials.push(newMaterial);
  23372. };
  23373. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23374. this.morphTargetManagers.push(newMorphTargetManager);
  23375. };
  23376. Scene.prototype.addGeometry = function (newGeometrie) {
  23377. this._geometries.push(newGeometrie);
  23378. };
  23379. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23380. this.lensFlareSystems.push(newLensFlareSystem);
  23381. };
  23382. Scene.prototype.addActionManager = function (newActionManager) {
  23383. this._actionManagers.push(newActionManager);
  23384. };
  23385. /**
  23386. * Switch active camera
  23387. * @param {Camera} newCamera - new active camera
  23388. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23389. */
  23390. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23391. if (attachControl === void 0) { attachControl = true; }
  23392. var canvas = this._engine.getRenderingCanvas();
  23393. if (!canvas) {
  23394. return;
  23395. }
  23396. if (this.activeCamera) {
  23397. this.activeCamera.detachControl(canvas);
  23398. }
  23399. this.activeCamera = newCamera;
  23400. if (attachControl) {
  23401. newCamera.attachControl(canvas);
  23402. }
  23403. };
  23404. /**
  23405. * sets the active camera of the scene using its ID
  23406. * @param {string} id - the camera's ID
  23407. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23408. * @see activeCamera
  23409. */
  23410. Scene.prototype.setActiveCameraByID = function (id) {
  23411. var camera = this.getCameraByID(id);
  23412. if (camera) {
  23413. this.activeCamera = camera;
  23414. return camera;
  23415. }
  23416. return null;
  23417. };
  23418. /**
  23419. * sets the active camera of the scene using its name
  23420. * @param {string} name - the camera's name
  23421. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23422. * @see activeCamera
  23423. */
  23424. Scene.prototype.setActiveCameraByName = function (name) {
  23425. var camera = this.getCameraByName(name);
  23426. if (camera) {
  23427. this.activeCamera = camera;
  23428. return camera;
  23429. }
  23430. return null;
  23431. };
  23432. /**
  23433. * get an animation group using its name
  23434. * @param {string} the material's name
  23435. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23436. */
  23437. Scene.prototype.getAnimationGroupByName = function (name) {
  23438. for (var index = 0; index < this.animationGroups.length; index++) {
  23439. if (this.animationGroups[index].name === name) {
  23440. return this.animationGroups[index];
  23441. }
  23442. }
  23443. return null;
  23444. };
  23445. /**
  23446. * get a material using its id
  23447. * @param {string} the material's ID
  23448. * @return {BABYLON.Material|null} the material or null if none found.
  23449. */
  23450. Scene.prototype.getMaterialByID = function (id) {
  23451. for (var index = 0; index < this.materials.length; index++) {
  23452. if (this.materials[index].id === id) {
  23453. return this.materials[index];
  23454. }
  23455. }
  23456. return null;
  23457. };
  23458. /**
  23459. * get a material using its name
  23460. * @param {string} the material's name
  23461. * @return {BABYLON.Material|null} the material or null if none found.
  23462. */
  23463. Scene.prototype.getMaterialByName = function (name) {
  23464. for (var index = 0; index < this.materials.length; index++) {
  23465. if (this.materials[index].name === name) {
  23466. return this.materials[index];
  23467. }
  23468. }
  23469. return null;
  23470. };
  23471. Scene.prototype.getLensFlareSystemByName = function (name) {
  23472. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23473. if (this.lensFlareSystems[index].name === name) {
  23474. return this.lensFlareSystems[index];
  23475. }
  23476. }
  23477. return null;
  23478. };
  23479. Scene.prototype.getLensFlareSystemByID = function (id) {
  23480. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23481. if (this.lensFlareSystems[index].id === id) {
  23482. return this.lensFlareSystems[index];
  23483. }
  23484. }
  23485. return null;
  23486. };
  23487. Scene.prototype.getCameraByID = function (id) {
  23488. for (var index = 0; index < this.cameras.length; index++) {
  23489. if (this.cameras[index].id === id) {
  23490. return this.cameras[index];
  23491. }
  23492. }
  23493. return null;
  23494. };
  23495. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23496. for (var index = 0; index < this.cameras.length; index++) {
  23497. if (this.cameras[index].uniqueId === uniqueId) {
  23498. return this.cameras[index];
  23499. }
  23500. }
  23501. return null;
  23502. };
  23503. /**
  23504. * get a camera using its name
  23505. * @param {string} the camera's name
  23506. * @return {BABYLON.Camera|null} the camera or null if none found.
  23507. */
  23508. Scene.prototype.getCameraByName = function (name) {
  23509. for (var index = 0; index < this.cameras.length; index++) {
  23510. if (this.cameras[index].name === name) {
  23511. return this.cameras[index];
  23512. }
  23513. }
  23514. return null;
  23515. };
  23516. /**
  23517. * get a bone using its id
  23518. * @param {string} the bone's id
  23519. * @return {BABYLON.Bone|null} the bone or null if not found
  23520. */
  23521. Scene.prototype.getBoneByID = function (id) {
  23522. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23523. var skeleton = this.skeletons[skeletonIndex];
  23524. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23525. if (skeleton.bones[boneIndex].id === id) {
  23526. return skeleton.bones[boneIndex];
  23527. }
  23528. }
  23529. }
  23530. return null;
  23531. };
  23532. /**
  23533. * get a bone using its id
  23534. * @param {string} the bone's name
  23535. * @return {BABYLON.Bone|null} the bone or null if not found
  23536. */
  23537. Scene.prototype.getBoneByName = function (name) {
  23538. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23539. var skeleton = this.skeletons[skeletonIndex];
  23540. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23541. if (skeleton.bones[boneIndex].name === name) {
  23542. return skeleton.bones[boneIndex];
  23543. }
  23544. }
  23545. }
  23546. return null;
  23547. };
  23548. /**
  23549. * get a light node using its name
  23550. * @param {string} the light's name
  23551. * @return {BABYLON.Light|null} the light or null if none found.
  23552. */
  23553. Scene.prototype.getLightByName = function (name) {
  23554. for (var index = 0; index < this.lights.length; index++) {
  23555. if (this.lights[index].name === name) {
  23556. return this.lights[index];
  23557. }
  23558. }
  23559. return null;
  23560. };
  23561. /**
  23562. * get a light node using its ID
  23563. * @param {string} the light's id
  23564. * @return {BABYLON.Light|null} the light or null if none found.
  23565. */
  23566. Scene.prototype.getLightByID = function (id) {
  23567. for (var index = 0; index < this.lights.length; index++) {
  23568. if (this.lights[index].id === id) {
  23569. return this.lights[index];
  23570. }
  23571. }
  23572. return null;
  23573. };
  23574. /**
  23575. * get a light node using its scene-generated unique ID
  23576. * @param {number} the light's unique id
  23577. * @return {BABYLON.Light|null} the light or null if none found.
  23578. */
  23579. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23580. for (var index = 0; index < this.lights.length; index++) {
  23581. if (this.lights[index].uniqueId === uniqueId) {
  23582. return this.lights[index];
  23583. }
  23584. }
  23585. return null;
  23586. };
  23587. /**
  23588. * get a particle system by id
  23589. * @param id {number} the particle system id
  23590. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23591. */
  23592. Scene.prototype.getParticleSystemByID = function (id) {
  23593. for (var index = 0; index < this.particleSystems.length; index++) {
  23594. if (this.particleSystems[index].id === id) {
  23595. return this.particleSystems[index];
  23596. }
  23597. }
  23598. return null;
  23599. };
  23600. /**
  23601. * get a geometry using its ID
  23602. * @param {string} the geometry's id
  23603. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23604. */
  23605. Scene.prototype.getGeometryByID = function (id) {
  23606. for (var index = 0; index < this._geometries.length; index++) {
  23607. if (this._geometries[index].id === id) {
  23608. return this._geometries[index];
  23609. }
  23610. }
  23611. return null;
  23612. };
  23613. /**
  23614. * add a new geometry to this scene.
  23615. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23616. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23617. * @return {boolean} was the geometry added or not
  23618. */
  23619. Scene.prototype.pushGeometry = function (geometry, force) {
  23620. if (!force && this.getGeometryByID(geometry.id)) {
  23621. return false;
  23622. }
  23623. this._geometries.push(geometry);
  23624. //notify the collision coordinator
  23625. if (this.collisionCoordinator) {
  23626. this.collisionCoordinator.onGeometryAdded(geometry);
  23627. }
  23628. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23629. return true;
  23630. };
  23631. /**
  23632. * Removes an existing geometry
  23633. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23634. * @return {boolean} was the geometry removed or not
  23635. */
  23636. Scene.prototype.removeGeometry = function (geometry) {
  23637. var index = this._geometries.indexOf(geometry);
  23638. if (index > -1) {
  23639. this._geometries.splice(index, 1);
  23640. //notify the collision coordinator
  23641. if (this.collisionCoordinator) {
  23642. this.collisionCoordinator.onGeometryDeleted(geometry);
  23643. }
  23644. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23645. return true;
  23646. }
  23647. return false;
  23648. };
  23649. Scene.prototype.getGeometries = function () {
  23650. return this._geometries;
  23651. };
  23652. /**
  23653. * Get the first added mesh found of a given ID
  23654. * @param {string} id - the id to search for
  23655. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23656. */
  23657. Scene.prototype.getMeshByID = function (id) {
  23658. for (var index = 0; index < this.meshes.length; index++) {
  23659. if (this.meshes[index].id === id) {
  23660. return this.meshes[index];
  23661. }
  23662. }
  23663. return null;
  23664. };
  23665. Scene.prototype.getMeshesByID = function (id) {
  23666. return this.meshes.filter(function (m) {
  23667. return m.id === id;
  23668. });
  23669. };
  23670. /**
  23671. * Get the first added transform node found of a given ID
  23672. * @param {string} id - the id to search for
  23673. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23674. */
  23675. Scene.prototype.getTransformNodeByID = function (id) {
  23676. for (var index = 0; index < this.transformNodes.length; index++) {
  23677. if (this.transformNodes[index].id === id) {
  23678. return this.transformNodes[index];
  23679. }
  23680. }
  23681. return null;
  23682. };
  23683. Scene.prototype.getTransformNodesByID = function (id) {
  23684. return this.transformNodes.filter(function (m) {
  23685. return m.id === id;
  23686. });
  23687. };
  23688. /**
  23689. * Get a mesh with its auto-generated unique id
  23690. * @param {number} uniqueId - the unique id to search for
  23691. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23692. */
  23693. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23694. for (var index = 0; index < this.meshes.length; index++) {
  23695. if (this.meshes[index].uniqueId === uniqueId) {
  23696. return this.meshes[index];
  23697. }
  23698. }
  23699. return null;
  23700. };
  23701. /**
  23702. * Get a the last added mesh found of a given ID
  23703. * @param {string} id - the id to search for
  23704. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23705. */
  23706. Scene.prototype.getLastMeshByID = function (id) {
  23707. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23708. if (this.meshes[index].id === id) {
  23709. return this.meshes[index];
  23710. }
  23711. }
  23712. return null;
  23713. };
  23714. /**
  23715. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23716. * @param {string} id - the id to search for
  23717. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23718. */
  23719. Scene.prototype.getLastEntryByID = function (id) {
  23720. var index;
  23721. for (index = this.meshes.length - 1; index >= 0; index--) {
  23722. if (this.meshes[index].id === id) {
  23723. return this.meshes[index];
  23724. }
  23725. }
  23726. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23727. if (this.transformNodes[index].id === id) {
  23728. return this.transformNodes[index];
  23729. }
  23730. }
  23731. for (index = this.cameras.length - 1; index >= 0; index--) {
  23732. if (this.cameras[index].id === id) {
  23733. return this.cameras[index];
  23734. }
  23735. }
  23736. for (index = this.lights.length - 1; index >= 0; index--) {
  23737. if (this.lights[index].id === id) {
  23738. return this.lights[index];
  23739. }
  23740. }
  23741. return null;
  23742. };
  23743. Scene.prototype.getNodeByID = function (id) {
  23744. var mesh = this.getMeshByID(id);
  23745. if (mesh) {
  23746. return mesh;
  23747. }
  23748. var light = this.getLightByID(id);
  23749. if (light) {
  23750. return light;
  23751. }
  23752. var camera = this.getCameraByID(id);
  23753. if (camera) {
  23754. return camera;
  23755. }
  23756. var bone = this.getBoneByID(id);
  23757. return bone;
  23758. };
  23759. Scene.prototype.getNodeByName = function (name) {
  23760. var mesh = this.getMeshByName(name);
  23761. if (mesh) {
  23762. return mesh;
  23763. }
  23764. var light = this.getLightByName(name);
  23765. if (light) {
  23766. return light;
  23767. }
  23768. var camera = this.getCameraByName(name);
  23769. if (camera) {
  23770. return camera;
  23771. }
  23772. var bone = this.getBoneByName(name);
  23773. return bone;
  23774. };
  23775. Scene.prototype.getMeshByName = function (name) {
  23776. for (var index = 0; index < this.meshes.length; index++) {
  23777. if (this.meshes[index].name === name) {
  23778. return this.meshes[index];
  23779. }
  23780. }
  23781. return null;
  23782. };
  23783. Scene.prototype.getTransformNodeByName = function (name) {
  23784. for (var index = 0; index < this.transformNodes.length; index++) {
  23785. if (this.transformNodes[index].name === name) {
  23786. return this.transformNodes[index];
  23787. }
  23788. }
  23789. return null;
  23790. };
  23791. Scene.prototype.getSoundByName = function (name) {
  23792. var index;
  23793. if (BABYLON.AudioEngine) {
  23794. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23795. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23796. return this.mainSoundTrack.soundCollection[index];
  23797. }
  23798. }
  23799. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23800. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23801. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23802. return this.soundTracks[sdIndex].soundCollection[index];
  23803. }
  23804. }
  23805. }
  23806. }
  23807. return null;
  23808. };
  23809. Scene.prototype.getLastSkeletonByID = function (id) {
  23810. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23811. if (this.skeletons[index].id === id) {
  23812. return this.skeletons[index];
  23813. }
  23814. }
  23815. return null;
  23816. };
  23817. Scene.prototype.getSkeletonById = function (id) {
  23818. for (var index = 0; index < this.skeletons.length; index++) {
  23819. if (this.skeletons[index].id === id) {
  23820. return this.skeletons[index];
  23821. }
  23822. }
  23823. return null;
  23824. };
  23825. Scene.prototype.getSkeletonByName = function (name) {
  23826. for (var index = 0; index < this.skeletons.length; index++) {
  23827. if (this.skeletons[index].name === name) {
  23828. return this.skeletons[index];
  23829. }
  23830. }
  23831. return null;
  23832. };
  23833. Scene.prototype.getMorphTargetManagerById = function (id) {
  23834. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23835. if (this.morphTargetManagers[index].uniqueId === id) {
  23836. return this.morphTargetManagers[index];
  23837. }
  23838. }
  23839. return null;
  23840. };
  23841. Scene.prototype.isActiveMesh = function (mesh) {
  23842. return (this._activeMeshes.indexOf(mesh) !== -1);
  23843. };
  23844. /**
  23845. * Return a the first highlight layer of the scene with a given name.
  23846. * @param name The name of the highlight layer to look for.
  23847. * @return The highlight layer if found otherwise null.
  23848. */
  23849. Scene.prototype.getHighlightLayerByName = function (name) {
  23850. for (var index = 0; index < this.effectLayers.length; index++) {
  23851. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23852. return this.effectLayers[index];
  23853. }
  23854. }
  23855. return null;
  23856. };
  23857. /**
  23858. * Return a the first highlight layer of the scene with a given name.
  23859. * @param name The name of the highlight layer to look for.
  23860. * @return The highlight layer if found otherwise null.
  23861. */
  23862. Scene.prototype.getGlowLayerByName = function (name) {
  23863. for (var index = 0; index < this.effectLayers.length; index++) {
  23864. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23865. return this.effectLayers[index];
  23866. }
  23867. }
  23868. return null;
  23869. };
  23870. Object.defineProperty(Scene.prototype, "uid", {
  23871. /**
  23872. * Return a unique id as a string which can serve as an identifier for the scene
  23873. */
  23874. get: function () {
  23875. if (!this._uid) {
  23876. this._uid = BABYLON.Tools.RandomId();
  23877. }
  23878. return this._uid;
  23879. },
  23880. enumerable: true,
  23881. configurable: true
  23882. });
  23883. /**
  23884. * Add an externaly attached data from its key.
  23885. * This method call will fail and return false, if such key already exists.
  23886. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23887. * @param key the unique key that identifies the data
  23888. * @param data the data object to associate to the key for this Engine instance
  23889. * @return true if no such key were already present and the data was added successfully, false otherwise
  23890. */
  23891. Scene.prototype.addExternalData = function (key, data) {
  23892. if (!this._externalData) {
  23893. this._externalData = new BABYLON.StringDictionary();
  23894. }
  23895. return this._externalData.add(key, data);
  23896. };
  23897. /**
  23898. * Get an externaly attached data from its key
  23899. * @param key the unique key that identifies the data
  23900. * @return the associated data, if present (can be null), or undefined if not present
  23901. */
  23902. Scene.prototype.getExternalData = function (key) {
  23903. if (!this._externalData) {
  23904. return null;
  23905. }
  23906. return this._externalData.get(key);
  23907. };
  23908. /**
  23909. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23910. * @param key the unique key that identifies the data
  23911. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23912. * @return the associated data, can be null if the factory returned null.
  23913. */
  23914. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23915. if (!this._externalData) {
  23916. this._externalData = new BABYLON.StringDictionary();
  23917. }
  23918. return this._externalData.getOrAddWithFactory(key, factory);
  23919. };
  23920. /**
  23921. * Remove an externaly attached data from the Engine instance
  23922. * @param key the unique key that identifies the data
  23923. * @return true if the data was successfully removed, false if it doesn't exist
  23924. */
  23925. Scene.prototype.removeExternalData = function (key) {
  23926. return this._externalData.remove(key);
  23927. };
  23928. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23929. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23930. if (mesh.showSubMeshesBoundingBox) {
  23931. var boundingInfo = subMesh.getBoundingInfo();
  23932. if (boundingInfo !== null && boundingInfo !== undefined) {
  23933. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23934. }
  23935. }
  23936. var material = subMesh.getMaterial();
  23937. if (material !== null && material !== undefined) {
  23938. // Render targets
  23939. if (material.getRenderTargetTextures !== undefined) {
  23940. if (this._processedMaterials.indexOf(material) === -1) {
  23941. this._processedMaterials.push(material);
  23942. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23943. }
  23944. }
  23945. // Dispatch
  23946. this._activeIndices.addCount(subMesh.indexCount, false);
  23947. this._renderingManager.dispatch(subMesh, mesh, material);
  23948. }
  23949. }
  23950. };
  23951. /**
  23952. * Clear the processed materials smart array preventing retention point in material dispose.
  23953. */
  23954. Scene.prototype.freeProcessedMaterials = function () {
  23955. this._processedMaterials.dispose();
  23956. };
  23957. /**
  23958. * Clear the active meshes smart array preventing retention point in mesh dispose.
  23959. */
  23960. Scene.prototype.freeActiveMeshes = function () {
  23961. this._activeMeshes.dispose();
  23962. if (this.activeCamera && this.activeCamera._activeMeshes) {
  23963. this.activeCamera._activeMeshes.dispose();
  23964. }
  23965. if (this.activeCameras) {
  23966. for (var i = 0; i < this.activeCameras.length; i++) {
  23967. var activeCamera = this.activeCameras[i];
  23968. if (activeCamera && activeCamera._activeMeshes) {
  23969. activeCamera._activeMeshes.dispose();
  23970. }
  23971. }
  23972. }
  23973. };
  23974. /**
  23975. * Clear the info related to rendering groups preventing retention points during dispose.
  23976. */
  23977. Scene.prototype.freeRenderingGroups = function () {
  23978. if (this._renderingManager) {
  23979. this._renderingManager.freeRenderingGroups();
  23980. }
  23981. if (this.textures) {
  23982. for (var i = 0; i < this.textures.length; i++) {
  23983. var texture = this.textures[i];
  23984. if (texture && texture.isRenderTarget) {
  23985. texture.freeRenderingGroups();
  23986. }
  23987. }
  23988. }
  23989. };
  23990. Scene.prototype._isInIntermediateRendering = function () {
  23991. return this._intermediateRendering;
  23992. };
  23993. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23994. this._activeMeshCandidateProvider = provider;
  23995. };
  23996. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23997. return this._activeMeshCandidateProvider;
  23998. };
  23999. /**
  24000. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24001. */
  24002. Scene.prototype.freezeActiveMeshes = function () {
  24003. this._evaluateActiveMeshes();
  24004. this._activeMeshesFrozen = true;
  24005. return this;
  24006. };
  24007. /**
  24008. * Use this function to restart evaluating active meshes on every frame
  24009. */
  24010. Scene.prototype.unfreezeActiveMeshes = function () {
  24011. this._activeMeshesFrozen = false;
  24012. return this;
  24013. };
  24014. Scene.prototype._evaluateActiveMeshes = function () {
  24015. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24016. return;
  24017. }
  24018. if (!this.activeCamera) {
  24019. return;
  24020. }
  24021. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24022. this.activeCamera._activeMeshes.reset();
  24023. this._activeMeshes.reset();
  24024. this._renderingManager.reset();
  24025. this._processedMaterials.reset();
  24026. this._activeParticleSystems.reset();
  24027. this._activeSkeletons.reset();
  24028. this._softwareSkinnedMeshes.reset();
  24029. if (this._boundingBoxRenderer) {
  24030. this._boundingBoxRenderer.reset();
  24031. }
  24032. // Meshes
  24033. var meshes;
  24034. var len;
  24035. var checkIsEnabled = true;
  24036. // Determine mesh candidates
  24037. if (this._activeMeshCandidateProvider !== undefined) {
  24038. // Use _activeMeshCandidateProvider
  24039. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24040. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24041. if (meshes !== undefined) {
  24042. len = meshes.length;
  24043. }
  24044. else {
  24045. len = 0;
  24046. }
  24047. }
  24048. else if (this._selectionOctree !== undefined) {
  24049. // Octree
  24050. var selection = this._selectionOctree.select(this._frustumPlanes);
  24051. meshes = selection.data;
  24052. len = selection.length;
  24053. }
  24054. else {
  24055. // Full scene traversal
  24056. len = this.meshes.length;
  24057. meshes = this.meshes;
  24058. }
  24059. // Check each mesh
  24060. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24061. mesh = meshes[meshIndex];
  24062. if (mesh.isBlocked) {
  24063. continue;
  24064. }
  24065. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24066. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24067. continue;
  24068. }
  24069. mesh.computeWorldMatrix();
  24070. // Intersections
  24071. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24072. this._meshesForIntersections.pushNoDuplicate(mesh);
  24073. }
  24074. // Switch to current LOD
  24075. meshLOD = mesh.getLOD(this.activeCamera);
  24076. if (meshLOD === undefined || meshLOD === null) {
  24077. continue;
  24078. }
  24079. mesh._preActivate();
  24080. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24081. this._activeMeshes.push(mesh);
  24082. this.activeCamera._activeMeshes.push(mesh);
  24083. mesh._activate(this._renderId);
  24084. if (meshLOD !== mesh) {
  24085. meshLOD._activate(this._renderId);
  24086. }
  24087. this._activeMesh(mesh, meshLOD);
  24088. }
  24089. }
  24090. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24091. // Particle systems
  24092. if (this.particlesEnabled) {
  24093. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24094. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24095. var particleSystem = this.particleSystems[particleIndex];
  24096. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24097. continue;
  24098. }
  24099. var emitter = particleSystem.emitter;
  24100. if (!emitter.position || emitter.isEnabled()) {
  24101. this._activeParticleSystems.push(particleSystem);
  24102. particleSystem.animate();
  24103. this._renderingManager.dispatchParticles(particleSystem);
  24104. }
  24105. }
  24106. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24107. }
  24108. };
  24109. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24110. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24111. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24112. mesh.skeleton.prepare();
  24113. }
  24114. if (!mesh.computeBonesUsingShaders) {
  24115. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24116. }
  24117. }
  24118. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24119. var boundingInfo = sourceMesh.getBoundingInfo();
  24120. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24121. }
  24122. if (mesh !== undefined && mesh !== null
  24123. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24124. // Submeshes Octrees
  24125. var len;
  24126. var subMeshes;
  24127. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24128. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24129. len = intersections.length;
  24130. subMeshes = intersections.data;
  24131. }
  24132. else {
  24133. subMeshes = mesh.subMeshes;
  24134. len = subMeshes.length;
  24135. }
  24136. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24137. subMesh = subMeshes[subIndex];
  24138. this._evaluateSubMesh(subMesh, mesh);
  24139. }
  24140. }
  24141. };
  24142. Scene.prototype.updateTransformMatrix = function (force) {
  24143. if (!this.activeCamera) {
  24144. return;
  24145. }
  24146. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24147. };
  24148. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24149. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24150. };
  24151. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24152. if (camera && camera._skipRendering) {
  24153. return;
  24154. }
  24155. var engine = this._engine;
  24156. this.activeCamera = camera;
  24157. if (!this.activeCamera)
  24158. throw new Error("Active camera not set");
  24159. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24160. // Viewport
  24161. engine.setViewport(this.activeCamera.viewport);
  24162. // Camera
  24163. this.resetCachedMaterial();
  24164. this._renderId++;
  24165. this.updateTransformMatrix();
  24166. if (camera._alternateCamera) {
  24167. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24168. this._alternateRendering = true;
  24169. }
  24170. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24171. // Meshes
  24172. this._evaluateActiveMeshes();
  24173. // Software skinning
  24174. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24175. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24176. mesh.applySkeleton(mesh.skeleton);
  24177. }
  24178. // Render targets
  24179. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24180. var needsRestoreFrameBuffer = false;
  24181. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24182. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24183. }
  24184. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24185. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24186. }
  24187. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24188. this._intermediateRendering = true;
  24189. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24190. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24191. var renderTarget = this._renderTargets.data[renderIndex];
  24192. if (renderTarget._shouldRender()) {
  24193. this._renderId++;
  24194. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24195. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24196. }
  24197. }
  24198. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24199. this._intermediateRendering = false;
  24200. this._renderId++;
  24201. needsRestoreFrameBuffer = true; // Restore back buffer
  24202. }
  24203. // Render EffecttLayer Texture
  24204. var stencilState = this._engine.getStencilBuffer();
  24205. var renderEffects = false;
  24206. var needStencil = false;
  24207. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24208. this._intermediateRendering = true;
  24209. for (var i = 0; i < this.effectLayers.length; i++) {
  24210. var effectLayer = this.effectLayers[i];
  24211. if (effectLayer.shouldRender() &&
  24212. (!effectLayer.camera ||
  24213. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24214. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24215. renderEffects = true;
  24216. needStencil = needStencil || effectLayer.needStencil();
  24217. var renderTarget = effectLayer._mainTexture;
  24218. if (renderTarget._shouldRender()) {
  24219. this._renderId++;
  24220. renderTarget.render(false, false);
  24221. needsRestoreFrameBuffer = true;
  24222. }
  24223. }
  24224. }
  24225. this._intermediateRendering = false;
  24226. this._renderId++;
  24227. }
  24228. if (needsRestoreFrameBuffer) {
  24229. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24230. }
  24231. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24232. // Prepare Frame
  24233. this.postProcessManager._prepareFrame();
  24234. // Backgrounds
  24235. var layerIndex;
  24236. var layer;
  24237. if (this.layers.length) {
  24238. engine.setDepthBuffer(false);
  24239. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24240. layer = this.layers[layerIndex];
  24241. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24242. layer.render();
  24243. }
  24244. }
  24245. engine.setDepthBuffer(true);
  24246. }
  24247. // Activate effect Layer stencil
  24248. if (needStencil) {
  24249. this._engine.setStencilBuffer(true);
  24250. }
  24251. // Render
  24252. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24253. this._renderingManager.render(null, null, true, true);
  24254. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24255. // Restore effect Layer stencil
  24256. if (needStencil) {
  24257. this._engine.setStencilBuffer(stencilState);
  24258. }
  24259. // Bounding boxes
  24260. if (this._boundingBoxRenderer) {
  24261. this._boundingBoxRenderer.render();
  24262. }
  24263. // Lens flares
  24264. if (this.lensFlaresEnabled) {
  24265. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24266. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24267. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24268. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24269. lensFlareSystem.render();
  24270. }
  24271. }
  24272. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24273. }
  24274. // Foregrounds
  24275. if (this.layers.length) {
  24276. engine.setDepthBuffer(false);
  24277. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24278. layer = this.layers[layerIndex];
  24279. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24280. layer.render();
  24281. }
  24282. }
  24283. engine.setDepthBuffer(true);
  24284. }
  24285. // Effect Layer
  24286. if (renderEffects) {
  24287. engine.setDepthBuffer(false);
  24288. for (var i = 0; i < this.effectLayers.length; i++) {
  24289. if (this.effectLayers[i].shouldRender()) {
  24290. this.effectLayers[i].render();
  24291. }
  24292. }
  24293. engine.setDepthBuffer(true);
  24294. }
  24295. // Finalize frame
  24296. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24297. // Reset some special arrays
  24298. this._renderTargets.reset();
  24299. this._alternateRendering = false;
  24300. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24301. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24302. };
  24303. Scene.prototype._processSubCameras = function (camera) {
  24304. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24305. this._renderForCamera(camera);
  24306. return;
  24307. }
  24308. // rig cameras
  24309. for (var index = 0; index < camera._rigCameras.length; index++) {
  24310. this._renderForCamera(camera._rigCameras[index], camera);
  24311. }
  24312. this.activeCamera = camera;
  24313. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24314. };
  24315. Scene.prototype._checkIntersections = function () {
  24316. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24317. var sourceMesh = this._meshesForIntersections.data[index];
  24318. if (!sourceMesh.actionManager) {
  24319. continue;
  24320. }
  24321. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24322. var action = sourceMesh.actionManager.actions[actionIndex];
  24323. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24324. var parameters = action.getTriggerParameter();
  24325. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24326. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24327. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24328. if (areIntersecting && currentIntersectionInProgress === -1) {
  24329. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24330. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24331. sourceMesh._intersectionsInProgress.push(otherMesh);
  24332. }
  24333. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24334. sourceMesh._intersectionsInProgress.push(otherMesh);
  24335. }
  24336. }
  24337. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24338. //They intersected, and now they don't.
  24339. //is this trigger an exit trigger? execute an event.
  24340. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24341. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24342. }
  24343. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24344. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24345. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24346. }
  24347. }
  24348. }
  24349. }
  24350. }
  24351. };
  24352. Scene.prototype.render = function () {
  24353. if (this.isDisposed) {
  24354. return;
  24355. }
  24356. this._activeParticles.fetchNewFrame();
  24357. this._totalVertices.fetchNewFrame();
  24358. this._activeIndices.fetchNewFrame();
  24359. this._activeBones.fetchNewFrame();
  24360. this._meshesForIntersections.reset();
  24361. this.resetCachedMaterial();
  24362. this.onBeforeAnimationsObservable.notifyObservers(this);
  24363. // Actions
  24364. if (this.actionManager) {
  24365. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24366. }
  24367. //Simplification Queue
  24368. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24369. this.simplificationQueue.executeNext();
  24370. }
  24371. if (this._engine.isDeterministicLockStep()) {
  24372. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24373. var defaultFPS = (60.0 / 1000.0);
  24374. var defaultFrameTime = 1000 / 60; // frame time in MS
  24375. if (this._physicsEngine) {
  24376. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24377. }
  24378. var stepsTaken = 0;
  24379. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24380. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24381. internalSteps = Math.min(internalSteps, maxSubSteps);
  24382. do {
  24383. this.onBeforeStepObservable.notifyObservers(this);
  24384. // Animations
  24385. this._animationRatio = defaultFrameTime * defaultFPS;
  24386. this._animate();
  24387. this.onAfterAnimationsObservable.notifyObservers(this);
  24388. // Physics
  24389. if (this._physicsEngine) {
  24390. this.onBeforePhysicsObservable.notifyObservers(this);
  24391. this._physicsEngine._step(defaultFrameTime / 1000);
  24392. this.onAfterPhysicsObservable.notifyObservers(this);
  24393. }
  24394. this.onAfterStepObservable.notifyObservers(this);
  24395. this._currentStepId++;
  24396. stepsTaken++;
  24397. deltaTime -= defaultFrameTime;
  24398. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24399. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24400. }
  24401. else {
  24402. // Animations
  24403. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24404. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24405. this._animate();
  24406. this.onAfterAnimationsObservable.notifyObservers(this);
  24407. // Physics
  24408. if (this._physicsEngine) {
  24409. this.onBeforePhysicsObservable.notifyObservers(this);
  24410. this._physicsEngine._step(deltaTime / 1000.0);
  24411. this.onAfterPhysicsObservable.notifyObservers(this);
  24412. }
  24413. }
  24414. // update gamepad manager
  24415. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24416. this._gamepadManager._checkGamepadsStatus();
  24417. }
  24418. // Update Cameras
  24419. if (this.activeCameras.length > 0) {
  24420. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24421. var camera = this.activeCameras[cameraIndex];
  24422. camera.update();
  24423. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24424. // rig cameras
  24425. for (var index = 0; index < camera._rigCameras.length; index++) {
  24426. camera._rigCameras[index].update();
  24427. }
  24428. }
  24429. }
  24430. }
  24431. else if (this.activeCamera) {
  24432. this.activeCamera.update();
  24433. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24434. // rig cameras
  24435. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24436. this.activeCamera._rigCameras[index].update();
  24437. }
  24438. }
  24439. }
  24440. // Before render
  24441. this.onBeforeRenderObservable.notifyObservers(this);
  24442. // Customs render targets
  24443. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24444. var engine = this.getEngine();
  24445. var currentActiveCamera = this.activeCamera;
  24446. if (this.renderTargetsEnabled) {
  24447. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24448. this._intermediateRendering = true;
  24449. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24450. var renderTarget = this.customRenderTargets[customIndex];
  24451. if (renderTarget._shouldRender()) {
  24452. this._renderId++;
  24453. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24454. if (!this.activeCamera)
  24455. throw new Error("Active camera not set");
  24456. // Viewport
  24457. engine.setViewport(this.activeCamera.viewport);
  24458. // Camera
  24459. this.updateTransformMatrix();
  24460. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24461. }
  24462. }
  24463. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24464. this._intermediateRendering = false;
  24465. this._renderId++;
  24466. }
  24467. // Restore back buffer
  24468. if (this.customRenderTargets.length > 0) {
  24469. engine.restoreDefaultFramebuffer();
  24470. }
  24471. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24472. this.activeCamera = currentActiveCamera;
  24473. // Procedural textures
  24474. if (this.proceduralTexturesEnabled) {
  24475. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24476. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24477. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24478. if (proceduralTexture._shouldRender()) {
  24479. proceduralTexture.render();
  24480. }
  24481. }
  24482. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24483. }
  24484. // Clear
  24485. if (this.autoClearDepthAndStencil || this.autoClear) {
  24486. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24487. }
  24488. // Shadows
  24489. if (this.shadowsEnabled) {
  24490. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24491. var light = this.lights[lightIndex];
  24492. var shadowGenerator = light.getShadowGenerator();
  24493. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24494. var shadowMap = (shadowGenerator.getShadowMap());
  24495. if (this.textures.indexOf(shadowMap) !== -1) {
  24496. this._renderTargets.push(shadowMap);
  24497. }
  24498. }
  24499. }
  24500. }
  24501. // Depth renderer
  24502. for (var key in this._depthRenderer) {
  24503. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24504. }
  24505. // Geometry renderer
  24506. if (this._geometryBufferRenderer) {
  24507. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24508. }
  24509. // RenderPipeline
  24510. if (this._postProcessRenderPipelineManager) {
  24511. this._postProcessRenderPipelineManager.update();
  24512. }
  24513. // Multi-cameras?
  24514. if (this.activeCameras.length > 0) {
  24515. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24516. if (cameraIndex > 0) {
  24517. this._engine.clear(null, false, true, true);
  24518. }
  24519. this._processSubCameras(this.activeCameras[cameraIndex]);
  24520. }
  24521. }
  24522. else {
  24523. if (!this.activeCamera) {
  24524. throw new Error("No camera defined");
  24525. }
  24526. this._processSubCameras(this.activeCamera);
  24527. }
  24528. // Intersection checks
  24529. this._checkIntersections();
  24530. // Update the audio listener attached to the camera
  24531. if (BABYLON.AudioEngine) {
  24532. this._updateAudioParameters();
  24533. }
  24534. // After render
  24535. if (this.afterRender) {
  24536. this.afterRender();
  24537. }
  24538. this.onAfterRenderObservable.notifyObservers(this);
  24539. // Cleaning
  24540. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24541. var data = this._toBeDisposed.data[index];
  24542. if (data) {
  24543. data.dispose();
  24544. }
  24545. this._toBeDisposed[index] = null;
  24546. }
  24547. this._toBeDisposed.reset();
  24548. if (this.dumpNextRenderTargets) {
  24549. this.dumpNextRenderTargets = false;
  24550. }
  24551. this._activeBones.addCount(0, true);
  24552. this._activeIndices.addCount(0, true);
  24553. this._activeParticles.addCount(0, true);
  24554. };
  24555. Scene.prototype._updateAudioParameters = function () {
  24556. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24557. return;
  24558. }
  24559. var listeningCamera;
  24560. var audioEngine = BABYLON.Engine.audioEngine;
  24561. if (this.activeCameras.length > 0) {
  24562. listeningCamera = this.activeCameras[0];
  24563. }
  24564. else {
  24565. listeningCamera = this.activeCamera;
  24566. }
  24567. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24568. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24569. // for VR cameras
  24570. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24571. listeningCamera = listeningCamera.rigCameras[0];
  24572. }
  24573. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24574. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24575. cameraDirection.normalize();
  24576. // To avoid some errors on GearVR
  24577. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24578. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24579. }
  24580. var i;
  24581. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24582. var sound = this.mainSoundTrack.soundCollection[i];
  24583. if (sound.useCustomAttenuation) {
  24584. sound.updateDistanceFromListener();
  24585. }
  24586. }
  24587. for (i = 0; i < this.soundTracks.length; i++) {
  24588. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24589. sound = this.soundTracks[i].soundCollection[j];
  24590. if (sound.useCustomAttenuation) {
  24591. sound.updateDistanceFromListener();
  24592. }
  24593. }
  24594. }
  24595. }
  24596. };
  24597. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24598. // Audio
  24599. get: function () {
  24600. return this._audioEnabled;
  24601. },
  24602. set: function (value) {
  24603. this._audioEnabled = value;
  24604. if (BABYLON.AudioEngine) {
  24605. if (this._audioEnabled) {
  24606. this._enableAudio();
  24607. }
  24608. else {
  24609. this._disableAudio();
  24610. }
  24611. }
  24612. },
  24613. enumerable: true,
  24614. configurable: true
  24615. });
  24616. Scene.prototype._disableAudio = function () {
  24617. var i;
  24618. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24619. this.mainSoundTrack.soundCollection[i].pause();
  24620. }
  24621. for (i = 0; i < this.soundTracks.length; i++) {
  24622. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24623. this.soundTracks[i].soundCollection[j].pause();
  24624. }
  24625. }
  24626. };
  24627. Scene.prototype._enableAudio = function () {
  24628. var i;
  24629. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24630. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24631. this.mainSoundTrack.soundCollection[i].play();
  24632. }
  24633. }
  24634. for (i = 0; i < this.soundTracks.length; i++) {
  24635. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24636. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24637. this.soundTracks[i].soundCollection[j].play();
  24638. }
  24639. }
  24640. }
  24641. };
  24642. Object.defineProperty(Scene.prototype, "headphone", {
  24643. get: function () {
  24644. return this._headphone;
  24645. },
  24646. set: function (value) {
  24647. this._headphone = value;
  24648. if (BABYLON.AudioEngine) {
  24649. if (this._headphone) {
  24650. this._switchAudioModeForHeadphones();
  24651. }
  24652. else {
  24653. this._switchAudioModeForNormalSpeakers();
  24654. }
  24655. }
  24656. },
  24657. enumerable: true,
  24658. configurable: true
  24659. });
  24660. Scene.prototype._switchAudioModeForHeadphones = function () {
  24661. this.mainSoundTrack.switchPanningModelToHRTF();
  24662. for (var i = 0; i < this.soundTracks.length; i++) {
  24663. this.soundTracks[i].switchPanningModelToHRTF();
  24664. }
  24665. };
  24666. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24667. this.mainSoundTrack.switchPanningModelToEqualPower();
  24668. for (var i = 0; i < this.soundTracks.length; i++) {
  24669. this.soundTracks[i].switchPanningModelToEqualPower();
  24670. }
  24671. };
  24672. /**
  24673. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24674. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24675. * @returns the created depth renderer
  24676. */
  24677. Scene.prototype.enableDepthRenderer = function (camera) {
  24678. camera = camera || this.activeCamera;
  24679. if (!camera) {
  24680. throw "No camera available to enable depth renderer";
  24681. }
  24682. if (!this._depthRenderer[camera.id]) {
  24683. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24684. }
  24685. return this._depthRenderer[camera.id];
  24686. };
  24687. /**
  24688. * Disables a depth renderer for a given camera
  24689. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24690. */
  24691. Scene.prototype.disableDepthRenderer = function (camera) {
  24692. camera = camera || this.activeCamera;
  24693. if (!camera || !this._depthRenderer[camera.id]) {
  24694. return;
  24695. }
  24696. this._depthRenderer[camera.id].dispose();
  24697. delete this._depthRenderer[camera.id];
  24698. };
  24699. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24700. if (ratio === void 0) { ratio = 1; }
  24701. if (this._geometryBufferRenderer) {
  24702. return this._geometryBufferRenderer;
  24703. }
  24704. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24705. if (!this._geometryBufferRenderer.isSupported) {
  24706. this._geometryBufferRenderer = null;
  24707. }
  24708. return this._geometryBufferRenderer;
  24709. };
  24710. Scene.prototype.disableGeometryBufferRenderer = function () {
  24711. if (!this._geometryBufferRenderer) {
  24712. return;
  24713. }
  24714. this._geometryBufferRenderer.dispose();
  24715. this._geometryBufferRenderer = null;
  24716. };
  24717. Scene.prototype.freezeMaterials = function () {
  24718. for (var i = 0; i < this.materials.length; i++) {
  24719. this.materials[i].freeze();
  24720. }
  24721. };
  24722. Scene.prototype.unfreezeMaterials = function () {
  24723. for (var i = 0; i < this.materials.length; i++) {
  24724. this.materials[i].unfreeze();
  24725. }
  24726. };
  24727. Scene.prototype.dispose = function () {
  24728. this.beforeRender = null;
  24729. this.afterRender = null;
  24730. this.skeletons = [];
  24731. this.morphTargetManagers = [];
  24732. this.importedMeshesFiles = new Array();
  24733. this.stopAllAnimations();
  24734. this.resetCachedMaterial();
  24735. for (var key in this._depthRenderer) {
  24736. this._depthRenderer[key].dispose();
  24737. }
  24738. if (this._gamepadManager) {
  24739. this._gamepadManager.dispose();
  24740. this._gamepadManager = null;
  24741. }
  24742. // Smart arrays
  24743. if (this.activeCamera) {
  24744. this.activeCamera._activeMeshes.dispose();
  24745. this.activeCamera = null;
  24746. }
  24747. this._activeMeshes.dispose();
  24748. this._renderingManager.dispose();
  24749. this._processedMaterials.dispose();
  24750. this._activeParticleSystems.dispose();
  24751. this._activeSkeletons.dispose();
  24752. this._softwareSkinnedMeshes.dispose();
  24753. this._renderTargets.dispose();
  24754. if (this._boundingBoxRenderer) {
  24755. this._boundingBoxRenderer.dispose();
  24756. }
  24757. this._meshesForIntersections.dispose();
  24758. this._toBeDisposed.dispose();
  24759. // Abort active requests
  24760. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24761. var request = _a[_i];
  24762. request.abort();
  24763. }
  24764. // Debug layer
  24765. if (this._debugLayer) {
  24766. this._debugLayer.hide();
  24767. }
  24768. // Events
  24769. this.onDisposeObservable.notifyObservers(this);
  24770. this.onDisposeObservable.clear();
  24771. this.onBeforeRenderObservable.clear();
  24772. this.onAfterRenderObservable.clear();
  24773. this.OnBeforeRenderTargetsRenderObservable.clear();
  24774. this.OnAfterRenderTargetsRenderObservable.clear();
  24775. this.onAfterStepObservable.clear();
  24776. this.onBeforeStepObservable.clear();
  24777. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24778. this.onAfterActiveMeshesEvaluationObservable.clear();
  24779. this.onBeforeParticlesRenderingObservable.clear();
  24780. this.onAfterParticlesRenderingObservable.clear();
  24781. this.onBeforeSpritesRenderingObservable.clear();
  24782. this.onAfterSpritesRenderingObservable.clear();
  24783. this.onBeforeDrawPhaseObservable.clear();
  24784. this.onAfterDrawPhaseObservable.clear();
  24785. this.onBeforePhysicsObservable.clear();
  24786. this.onAfterPhysicsObservable.clear();
  24787. this.onBeforeAnimationsObservable.clear();
  24788. this.onAfterAnimationsObservable.clear();
  24789. this.onDataLoadedObservable.clear();
  24790. this.detachControl();
  24791. // Release sounds & sounds tracks
  24792. if (BABYLON.AudioEngine) {
  24793. this.disposeSounds();
  24794. }
  24795. // VR Helper
  24796. if (this.VRHelper) {
  24797. this.VRHelper.dispose();
  24798. }
  24799. // Detach cameras
  24800. var canvas = this._engine.getRenderingCanvas();
  24801. if (canvas) {
  24802. var index;
  24803. for (index = 0; index < this.cameras.length; index++) {
  24804. this.cameras[index].detachControl(canvas);
  24805. }
  24806. }
  24807. // Release animation groups
  24808. while (this.animationGroups.length) {
  24809. this.animationGroups[0].dispose();
  24810. }
  24811. // Release lights
  24812. while (this.lights.length) {
  24813. this.lights[0].dispose();
  24814. }
  24815. // Release meshes
  24816. while (this.meshes.length) {
  24817. this.meshes[0].dispose(true);
  24818. }
  24819. while (this.transformNodes.length) {
  24820. this.removeTransformNode(this.transformNodes[0]);
  24821. }
  24822. // Release cameras
  24823. while (this.cameras.length) {
  24824. this.cameras[0].dispose();
  24825. }
  24826. // Release materials
  24827. if (this.defaultMaterial) {
  24828. this.defaultMaterial.dispose();
  24829. }
  24830. while (this.multiMaterials.length) {
  24831. this.multiMaterials[0].dispose();
  24832. }
  24833. while (this.materials.length) {
  24834. this.materials[0].dispose();
  24835. }
  24836. // Release particles
  24837. while (this.particleSystems.length) {
  24838. this.particleSystems[0].dispose();
  24839. }
  24840. // Release sprites
  24841. while (this.spriteManagers.length) {
  24842. this.spriteManagers[0].dispose();
  24843. }
  24844. // Release postProcesses
  24845. while (this.postProcesses.length) {
  24846. this.postProcesses[0].dispose();
  24847. }
  24848. // Release layers
  24849. while (this.layers.length) {
  24850. this.layers[0].dispose();
  24851. }
  24852. while (this.effectLayers.length) {
  24853. this.effectLayers[0].dispose();
  24854. }
  24855. // Release textures
  24856. while (this.textures.length) {
  24857. this.textures[0].dispose();
  24858. }
  24859. // Release UBO
  24860. this._sceneUbo.dispose();
  24861. if (this._alternateSceneUbo) {
  24862. this._alternateSceneUbo.dispose();
  24863. }
  24864. // Post-processes
  24865. this.postProcessManager.dispose();
  24866. if (this._postProcessRenderPipelineManager) {
  24867. this._postProcessRenderPipelineManager.dispose();
  24868. }
  24869. // Physics
  24870. if (this._physicsEngine) {
  24871. this.disablePhysicsEngine();
  24872. }
  24873. // Remove from engine
  24874. index = this._engine.scenes.indexOf(this);
  24875. if (index > -1) {
  24876. this._engine.scenes.splice(index, 1);
  24877. }
  24878. this._engine.wipeCaches(true);
  24879. this._isDisposed = true;
  24880. };
  24881. Object.defineProperty(Scene.prototype, "isDisposed", {
  24882. get: function () {
  24883. return this._isDisposed;
  24884. },
  24885. enumerable: true,
  24886. configurable: true
  24887. });
  24888. // Release sounds & sounds tracks
  24889. Scene.prototype.disposeSounds = function () {
  24890. if (!this._mainSoundTrack) {
  24891. return;
  24892. }
  24893. this.mainSoundTrack.dispose();
  24894. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24895. this.soundTracks[scIndex].dispose();
  24896. }
  24897. };
  24898. // Octrees
  24899. /**
  24900. * Get the world extend vectors with an optional filter
  24901. *
  24902. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24903. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24904. */
  24905. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24906. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24907. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24908. filterPredicate = filterPredicate || (function () { return true; });
  24909. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24910. mesh.computeWorldMatrix(true);
  24911. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24912. return;
  24913. }
  24914. var boundingInfo = mesh.getBoundingInfo();
  24915. var minBox = boundingInfo.boundingBox.minimumWorld;
  24916. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24917. BABYLON.Tools.CheckExtends(minBox, min, max);
  24918. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24919. });
  24920. return {
  24921. min: min,
  24922. max: max
  24923. };
  24924. };
  24925. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24926. if (maxCapacity === void 0) { maxCapacity = 64; }
  24927. if (maxDepth === void 0) { maxDepth = 2; }
  24928. if (!this._selectionOctree) {
  24929. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24930. }
  24931. var worldExtends = this.getWorldExtends();
  24932. // Update octree
  24933. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24934. return this._selectionOctree;
  24935. };
  24936. // Picking
  24937. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24938. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24939. var result = BABYLON.Ray.Zero();
  24940. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24941. return result;
  24942. };
  24943. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24944. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24945. var engine = this._engine;
  24946. if (!camera) {
  24947. if (!this.activeCamera)
  24948. throw new Error("Active camera not set");
  24949. camera = this.activeCamera;
  24950. }
  24951. var cameraViewport = camera.viewport;
  24952. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24953. // Moving coordinates to local viewport world
  24954. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24955. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24956. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24957. return this;
  24958. };
  24959. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24960. var result = BABYLON.Ray.Zero();
  24961. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24962. return result;
  24963. };
  24964. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24965. if (!BABYLON.PickingInfo) {
  24966. return this;
  24967. }
  24968. var engine = this._engine;
  24969. if (!camera) {
  24970. if (!this.activeCamera)
  24971. throw new Error("Active camera not set");
  24972. camera = this.activeCamera;
  24973. }
  24974. var cameraViewport = camera.viewport;
  24975. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24976. var identity = BABYLON.Matrix.Identity();
  24977. // Moving coordinates to local viewport world
  24978. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24979. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24980. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24981. return this;
  24982. };
  24983. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24984. if (!BABYLON.PickingInfo) {
  24985. return null;
  24986. }
  24987. var pickingInfo = null;
  24988. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24989. var mesh = this.meshes[meshIndex];
  24990. if (predicate) {
  24991. if (!predicate(mesh)) {
  24992. continue;
  24993. }
  24994. }
  24995. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24996. continue;
  24997. }
  24998. var world = mesh.getWorldMatrix();
  24999. var ray = rayFunction(world);
  25000. var result = mesh.intersects(ray, fastCheck);
  25001. if (!result || !result.hit)
  25002. continue;
  25003. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25004. continue;
  25005. pickingInfo = result;
  25006. if (fastCheck) {
  25007. break;
  25008. }
  25009. }
  25010. return pickingInfo || new BABYLON.PickingInfo();
  25011. };
  25012. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25013. if (!BABYLON.PickingInfo) {
  25014. return null;
  25015. }
  25016. var pickingInfos = new Array();
  25017. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25018. var mesh = this.meshes[meshIndex];
  25019. if (predicate) {
  25020. if (!predicate(mesh)) {
  25021. continue;
  25022. }
  25023. }
  25024. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25025. continue;
  25026. }
  25027. var world = mesh.getWorldMatrix();
  25028. var ray = rayFunction(world);
  25029. var result = mesh.intersects(ray, false);
  25030. if (!result || !result.hit)
  25031. continue;
  25032. pickingInfos.push(result);
  25033. }
  25034. return pickingInfos;
  25035. };
  25036. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25037. if (!BABYLON.PickingInfo) {
  25038. return null;
  25039. }
  25040. var pickingInfo = null;
  25041. if (!camera) {
  25042. if (!this.activeCamera) {
  25043. return null;
  25044. }
  25045. camera = this.activeCamera;
  25046. }
  25047. if (this.spriteManagers.length > 0) {
  25048. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25049. var spriteManager = this.spriteManagers[spriteIndex];
  25050. if (!spriteManager.isPickable) {
  25051. continue;
  25052. }
  25053. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25054. if (!result || !result.hit)
  25055. continue;
  25056. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25057. continue;
  25058. pickingInfo = result;
  25059. if (fastCheck) {
  25060. break;
  25061. }
  25062. }
  25063. }
  25064. return pickingInfo || new BABYLON.PickingInfo();
  25065. };
  25066. /** Launch a ray to try to pick a mesh in the scene
  25067. * @param x position on screen
  25068. * @param y position on screen
  25069. * @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
  25070. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25071. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25072. */
  25073. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25074. var _this = this;
  25075. if (!BABYLON.PickingInfo) {
  25076. return null;
  25077. }
  25078. return this._internalPick(function (world) {
  25079. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25080. return _this._tempPickingRay;
  25081. }, predicate, fastCheck);
  25082. };
  25083. /** Launch a ray to try to pick a sprite in the scene
  25084. * @param x position on screen
  25085. * @param y position on screen
  25086. * @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
  25087. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25088. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25089. */
  25090. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25091. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25092. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25093. };
  25094. /** Use the given ray to pick a mesh in the scene
  25095. * @param ray The ray to use to pick meshes
  25096. * @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
  25097. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25098. */
  25099. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25100. var _this = this;
  25101. return this._internalPick(function (world) {
  25102. if (!_this._pickWithRayInverseMatrix) {
  25103. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25104. }
  25105. world.invertToRef(_this._pickWithRayInverseMatrix);
  25106. if (!_this._cachedRayForTransform) {
  25107. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25108. }
  25109. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25110. return _this._cachedRayForTransform;
  25111. }, predicate, fastCheck);
  25112. };
  25113. /**
  25114. * Launch a ray to try to pick a mesh in the scene
  25115. * @param x X position on screen
  25116. * @param y Y position on screen
  25117. * @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
  25118. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25119. */
  25120. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25121. var _this = this;
  25122. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25123. };
  25124. /**
  25125. * Launch a ray to try to pick a mesh in the scene
  25126. * @param ray Ray to use
  25127. * @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
  25128. */
  25129. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25130. var _this = this;
  25131. return this._internalMultiPick(function (world) {
  25132. if (!_this._pickWithRayInverseMatrix) {
  25133. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25134. }
  25135. world.invertToRef(_this._pickWithRayInverseMatrix);
  25136. if (!_this._cachedRayForTransform) {
  25137. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25138. }
  25139. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25140. return _this._cachedRayForTransform;
  25141. }, predicate);
  25142. };
  25143. Scene.prototype.setPointerOverMesh = function (mesh) {
  25144. if (this._pointerOverMesh === mesh) {
  25145. return;
  25146. }
  25147. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25148. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25149. }
  25150. this._pointerOverMesh = mesh;
  25151. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25152. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25153. }
  25154. };
  25155. Scene.prototype.getPointerOverMesh = function () {
  25156. return this._pointerOverMesh;
  25157. };
  25158. Scene.prototype.setPointerOverSprite = function (sprite) {
  25159. if (this._pointerOverSprite === sprite) {
  25160. return;
  25161. }
  25162. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25163. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25164. }
  25165. this._pointerOverSprite = sprite;
  25166. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25167. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25168. }
  25169. };
  25170. Scene.prototype.getPointerOverSprite = function () {
  25171. return this._pointerOverSprite;
  25172. };
  25173. // Physics
  25174. Scene.prototype.getPhysicsEngine = function () {
  25175. return this._physicsEngine;
  25176. };
  25177. /**
  25178. * Enables physics to the current scene
  25179. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25180. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25181. * @return {boolean} was the physics engine initialized
  25182. */
  25183. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25184. if (gravity === void 0) { gravity = null; }
  25185. if (this._physicsEngine) {
  25186. return true;
  25187. }
  25188. try {
  25189. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25190. return true;
  25191. }
  25192. catch (e) {
  25193. BABYLON.Tools.Error(e.message);
  25194. return false;
  25195. }
  25196. };
  25197. Scene.prototype.disablePhysicsEngine = function () {
  25198. if (!this._physicsEngine) {
  25199. return;
  25200. }
  25201. this._physicsEngine.dispose();
  25202. this._physicsEngine = null;
  25203. };
  25204. Scene.prototype.isPhysicsEnabled = function () {
  25205. return this._physicsEngine !== undefined;
  25206. };
  25207. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25208. var mesh = compound.parts[0].mesh;
  25209. if (mesh.physicsImpostor) {
  25210. mesh.physicsImpostor.dispose();
  25211. mesh.physicsImpostor = null;
  25212. }
  25213. };
  25214. // Misc.
  25215. Scene.prototype._rebuildGeometries = function () {
  25216. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25217. var geometry = _a[_i];
  25218. geometry._rebuild();
  25219. }
  25220. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25221. var mesh = _c[_b];
  25222. mesh._rebuild();
  25223. }
  25224. if (this.postProcessManager) {
  25225. this.postProcessManager._rebuild();
  25226. }
  25227. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25228. var layer = _e[_d];
  25229. layer._rebuild();
  25230. }
  25231. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25232. var effectLayer = _g[_f];
  25233. effectLayer._rebuild();
  25234. }
  25235. if (this._boundingBoxRenderer) {
  25236. this._boundingBoxRenderer._rebuild();
  25237. }
  25238. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25239. var system = _j[_h];
  25240. system.rebuild();
  25241. }
  25242. if (this._postProcessRenderPipelineManager) {
  25243. this._postProcessRenderPipelineManager._rebuild();
  25244. }
  25245. };
  25246. Scene.prototype._rebuildTextures = function () {
  25247. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25248. var texture = _a[_i];
  25249. texture._rebuild();
  25250. }
  25251. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25252. };
  25253. /**
  25254. * Creates a default light for the scene.
  25255. * @param replace Whether to replace the existing lights in the scene.
  25256. */
  25257. Scene.prototype.createDefaultLight = function (replace) {
  25258. if (replace === void 0) { replace = false; }
  25259. // Dispose existing light in replace mode.
  25260. if (replace) {
  25261. if (this.lights) {
  25262. for (var i = 0; i < this.lights.length; i++) {
  25263. this.lights[i].dispose();
  25264. }
  25265. }
  25266. }
  25267. // Light
  25268. if (this.lights.length === 0) {
  25269. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25270. }
  25271. };
  25272. /**
  25273. * Creates a default camera for the scene.
  25274. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25275. * @param replace Whether to replace the existing active camera in the scene.
  25276. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25277. */
  25278. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25279. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25280. if (replace === void 0) { replace = false; }
  25281. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25282. // Dispose existing camera in replace mode.
  25283. if (replace) {
  25284. if (this.activeCamera) {
  25285. this.activeCamera.dispose();
  25286. this.activeCamera = null;
  25287. }
  25288. }
  25289. // Camera
  25290. if (!this.activeCamera) {
  25291. var worldExtends = this.getWorldExtends();
  25292. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25293. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25294. var camera;
  25295. var radius = worldSize.length() * 1.5;
  25296. // empty scene scenario!
  25297. if (!isFinite(radius)) {
  25298. radius = 1;
  25299. worldCenter.copyFromFloats(0, 0, 0);
  25300. }
  25301. if (createArcRotateCamera) {
  25302. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25303. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25304. arcRotateCamera.wheelPrecision = 100 / radius;
  25305. camera = arcRotateCamera;
  25306. }
  25307. else {
  25308. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25309. freeCamera.setTarget(worldCenter);
  25310. camera = freeCamera;
  25311. }
  25312. camera.minZ = radius * 0.01;
  25313. camera.maxZ = radius * 1000;
  25314. camera.speed = radius * 0.2;
  25315. this.activeCamera = camera;
  25316. var canvas = this.getEngine().getRenderingCanvas();
  25317. if (attachCameraControls && canvas) {
  25318. camera.attachControl(canvas);
  25319. }
  25320. }
  25321. };
  25322. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25323. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25324. if (replace === void 0) { replace = false; }
  25325. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25326. this.createDefaultLight(replace);
  25327. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25328. };
  25329. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25330. if (pbr === void 0) { pbr = false; }
  25331. if (scale === void 0) { scale = 1000; }
  25332. if (blur === void 0) { blur = 0; }
  25333. if (environmentTexture) {
  25334. this.environmentTexture = environmentTexture;
  25335. }
  25336. if (!this.environmentTexture) {
  25337. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25338. return null;
  25339. }
  25340. // Skybox
  25341. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25342. if (pbr) {
  25343. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25344. hdrSkyboxMaterial.backFaceCulling = false;
  25345. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25346. if (hdrSkyboxMaterial.reflectionTexture) {
  25347. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25348. }
  25349. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25350. hdrSkyboxMaterial.disableLighting = true;
  25351. hdrSkyboxMaterial.twoSidedLighting = true;
  25352. hdrSkybox.infiniteDistance = true;
  25353. hdrSkybox.material = hdrSkyboxMaterial;
  25354. }
  25355. else {
  25356. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25357. skyboxMaterial.backFaceCulling = false;
  25358. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25359. if (skyboxMaterial.reflectionTexture) {
  25360. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25361. }
  25362. skyboxMaterial.disableLighting = true;
  25363. hdrSkybox.infiniteDistance = true;
  25364. hdrSkybox.material = skyboxMaterial;
  25365. }
  25366. return hdrSkybox;
  25367. };
  25368. Scene.prototype.createDefaultEnvironment = function (options) {
  25369. if (BABYLON.EnvironmentHelper) {
  25370. return new BABYLON.EnvironmentHelper(options, this);
  25371. }
  25372. return null;
  25373. };
  25374. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25375. if (webVROptions === void 0) { webVROptions = {}; }
  25376. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25377. };
  25378. // Tags
  25379. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25380. if (tagsQuery === undefined) {
  25381. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25382. return list;
  25383. }
  25384. var listByTags = [];
  25385. forEach = forEach || (function (item) { return; });
  25386. for (var i in list) {
  25387. var item = list[i];
  25388. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25389. listByTags.push(item);
  25390. forEach(item);
  25391. }
  25392. }
  25393. return listByTags;
  25394. };
  25395. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25396. return this._getByTags(this.meshes, tagsQuery, forEach);
  25397. };
  25398. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25399. return this._getByTags(this.cameras, tagsQuery, forEach);
  25400. };
  25401. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25402. return this._getByTags(this.lights, tagsQuery, forEach);
  25403. };
  25404. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25405. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25406. };
  25407. /**
  25408. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25409. * This allowed control for front to back rendering or reversly depending of the special needs.
  25410. *
  25411. * @param renderingGroupId The rendering group id corresponding to its index
  25412. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25413. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25414. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25415. */
  25416. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25417. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25418. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25419. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25420. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25421. };
  25422. /**
  25423. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25424. *
  25425. * @param renderingGroupId The rendering group id corresponding to its index
  25426. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25427. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25428. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25429. */
  25430. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25431. if (depth === void 0) { depth = true; }
  25432. if (stencil === void 0) { stencil = true; }
  25433. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25434. };
  25435. /**
  25436. * Will flag all materials as dirty to trigger new shader compilation
  25437. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25438. */
  25439. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25440. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25441. var material = _a[_i];
  25442. if (predicate && !predicate(material)) {
  25443. continue;
  25444. }
  25445. material.markAsDirty(flag);
  25446. }
  25447. };
  25448. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25449. var _this = this;
  25450. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25451. this._activeRequests.push(request);
  25452. request.onCompleteObservable.add(function (request) {
  25453. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25454. });
  25455. return request;
  25456. };
  25457. /** @ignore */
  25458. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25459. var _this = this;
  25460. return new Promise(function (resolve, reject) {
  25461. _this._loadFile(url, function (data) {
  25462. resolve(data);
  25463. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25464. reject(exception);
  25465. });
  25466. });
  25467. };
  25468. // Statics
  25469. Scene._FOGMODE_NONE = 0;
  25470. Scene._FOGMODE_EXP = 1;
  25471. Scene._FOGMODE_EXP2 = 2;
  25472. Scene._FOGMODE_LINEAR = 3;
  25473. Scene._uniqueIdCounter = 0;
  25474. Scene.MinDeltaTime = 1.0;
  25475. Scene.MaxDeltaTime = 1000.0;
  25476. /** The distance in pixel that you have to move to prevent some events */
  25477. Scene.DragMovementThreshold = 10; // in pixels
  25478. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25479. Scene.LongPressDelay = 500; // in milliseconds
  25480. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25481. Scene.DoubleClickDelay = 300; // in milliseconds
  25482. /** If you need to check double click without raising a single click at first click, enable this flag */
  25483. Scene.ExclusiveDoubleClickMode = false;
  25484. return Scene;
  25485. }());
  25486. BABYLON.Scene = Scene;
  25487. })(BABYLON || (BABYLON = {}));
  25488. //# sourceMappingURL=babylon.scene.js.map
  25489. var BABYLON;
  25490. (function (BABYLON) {
  25491. /**
  25492. * Set of assets to keep when moving a scene into an asset container.
  25493. */
  25494. var KeepAssets = /** @class */ (function () {
  25495. function KeepAssets() {
  25496. /**
  25497. * Cameras to keep.
  25498. */
  25499. this.cameras = new Array();
  25500. /**
  25501. * Lights to keep.
  25502. */
  25503. this.lights = new Array();
  25504. /**
  25505. * Meshes to keep.
  25506. */
  25507. this.meshes = new Array();
  25508. /**
  25509. * Skeletons to keep.
  25510. */
  25511. this.skeletons = new Array();
  25512. /**
  25513. * ParticleSystems to keep.
  25514. */
  25515. this.particleSystems = new Array();
  25516. /**
  25517. * Animations to keep.
  25518. */
  25519. this.animations = new Array();
  25520. /**
  25521. * MultiMaterials to keep.
  25522. */
  25523. this.multiMaterials = new Array();
  25524. /**
  25525. * Materials to keep.
  25526. */
  25527. this.materials = new Array();
  25528. /**
  25529. * MorphTargetManagers to keep.
  25530. */
  25531. this.morphTargetManagers = new Array();
  25532. /**
  25533. * Geometries to keep.
  25534. */
  25535. this.geometries = new Array();
  25536. /**
  25537. * TransformNodes to keep.
  25538. */
  25539. this.transformNodes = new Array();
  25540. /**
  25541. * LensFlareSystems to keep.
  25542. */
  25543. this.lensFlareSystems = new Array();
  25544. /**
  25545. * ShadowGenerators to keep.
  25546. */
  25547. this.shadowGenerators = new Array();
  25548. /**
  25549. * ActionManagers to keep.
  25550. */
  25551. this.actionManagers = new Array();
  25552. /**
  25553. * Sounds to keep.
  25554. */
  25555. this.sounds = new Array();
  25556. }
  25557. return KeepAssets;
  25558. }());
  25559. BABYLON.KeepAssets = KeepAssets;
  25560. /**
  25561. * Container with a set of assets that can be added or removed from a scene.
  25562. */
  25563. var AssetContainer = /** @class */ (function () {
  25564. /**
  25565. * Instantiates an AssetContainer.
  25566. * @param scene The scene the AssetContainer belongs to.
  25567. */
  25568. function AssetContainer(scene) {
  25569. // Objects
  25570. /**
  25571. * Cameras populated in the container.
  25572. */
  25573. this.cameras = new Array();
  25574. /**
  25575. * Lights populated in the container.
  25576. */
  25577. this.lights = new Array();
  25578. /**
  25579. * Meshes populated in the container.
  25580. */
  25581. this.meshes = new Array();
  25582. /**
  25583. * Skeletons populated in the container.
  25584. */
  25585. this.skeletons = new Array();
  25586. /**
  25587. * ParticleSystems populated in the container.
  25588. */
  25589. this.particleSystems = new Array();
  25590. /**
  25591. * Animations populated in the container.
  25592. */
  25593. this.animations = new Array();
  25594. /**
  25595. * MultiMaterials populated in the container.
  25596. */
  25597. this.multiMaterials = new Array();
  25598. /**
  25599. * Materials populated in the container.
  25600. */
  25601. this.materials = new Array();
  25602. /**
  25603. * MorphTargetManagers populated in the container.
  25604. */
  25605. this.morphTargetManagers = new Array();
  25606. /**
  25607. * Geometries populated in the container.
  25608. */
  25609. this.geometries = new Array();
  25610. /**
  25611. * TransformNodes populated in the container.
  25612. */
  25613. this.transformNodes = new Array();
  25614. /**
  25615. * LensFlareSystems populated in the container.
  25616. */
  25617. this.lensFlareSystems = new Array();
  25618. /**
  25619. * ShadowGenerators populated in the container.
  25620. */
  25621. this.shadowGenerators = new Array();
  25622. /**
  25623. * ActionManagers populated in the container.
  25624. */
  25625. this.actionManagers = new Array();
  25626. /**
  25627. * Sounds populated in the container.
  25628. */
  25629. this.sounds = new Array();
  25630. this.scene = scene;
  25631. }
  25632. /**
  25633. * Adds all the assets from the container to the scene.
  25634. */
  25635. AssetContainer.prototype.addAllToScene = function () {
  25636. var _this = this;
  25637. this.cameras.forEach(function (o) {
  25638. _this.scene.addCamera(o);
  25639. });
  25640. this.lights.forEach(function (o) {
  25641. _this.scene.addLight(o);
  25642. });
  25643. this.meshes.forEach(function (o) {
  25644. _this.scene.addMesh(o);
  25645. });
  25646. this.skeletons.forEach(function (o) {
  25647. _this.scene.addSkeleton(o);
  25648. });
  25649. this.particleSystems.forEach(function (o) {
  25650. _this.scene.addParticleSystem(o);
  25651. });
  25652. this.animations.forEach(function (o) {
  25653. _this.scene.addAnimation(o);
  25654. });
  25655. this.multiMaterials.forEach(function (o) {
  25656. _this.scene.addMultiMaterial(o);
  25657. });
  25658. this.materials.forEach(function (o) {
  25659. _this.scene.addMaterial(o);
  25660. });
  25661. this.morphTargetManagers.forEach(function (o) {
  25662. _this.scene.addMorphTargetManager(o);
  25663. });
  25664. this.geometries.forEach(function (o) {
  25665. _this.scene.addGeometry(o);
  25666. });
  25667. this.transformNodes.forEach(function (o) {
  25668. _this.scene.addTransformNode(o);
  25669. });
  25670. this.lensFlareSystems.forEach(function (o) {
  25671. _this.scene.addLensFlareSystem(o);
  25672. });
  25673. this.actionManagers.forEach(function (o) {
  25674. _this.scene.addActionManager(o);
  25675. });
  25676. this.sounds.forEach(function (o) {
  25677. o.play();
  25678. o.autoplay = true;
  25679. _this.scene.mainSoundTrack.AddSound(o);
  25680. });
  25681. };
  25682. /**
  25683. * Removes all the assets in the container from the scene
  25684. */
  25685. AssetContainer.prototype.removeAllFromScene = function () {
  25686. var _this = this;
  25687. this.cameras.forEach(function (o) {
  25688. _this.scene.removeCamera(o);
  25689. });
  25690. this.lights.forEach(function (o) {
  25691. _this.scene.removeLight(o);
  25692. });
  25693. this.meshes.forEach(function (o) {
  25694. _this.scene.removeMesh(o);
  25695. });
  25696. this.skeletons.forEach(function (o) {
  25697. _this.scene.removeSkeleton(o);
  25698. });
  25699. this.particleSystems.forEach(function (o) {
  25700. _this.scene.removeParticleSystem(o);
  25701. });
  25702. this.animations.forEach(function (o) {
  25703. _this.scene.removeAnimation(o);
  25704. });
  25705. this.multiMaterials.forEach(function (o) {
  25706. _this.scene.removeMultiMaterial(o);
  25707. });
  25708. this.materials.forEach(function (o) {
  25709. _this.scene.removeMaterial(o);
  25710. });
  25711. this.morphTargetManagers.forEach(function (o) {
  25712. _this.scene.removeMorphTargetManager(o);
  25713. });
  25714. this.geometries.forEach(function (o) {
  25715. _this.scene.removeGeometry(o);
  25716. });
  25717. this.transformNodes.forEach(function (o) {
  25718. _this.scene.removeTransformNode(o);
  25719. });
  25720. this.lensFlareSystems.forEach(function (o) {
  25721. _this.scene.removeLensFlareSystem(o);
  25722. });
  25723. this.actionManagers.forEach(function (o) {
  25724. _this.scene.removeActionManager(o);
  25725. });
  25726. this.sounds.forEach(function (o) {
  25727. o.stop();
  25728. o.autoplay = false;
  25729. _this.scene.mainSoundTrack.RemoveSound(o);
  25730. });
  25731. };
  25732. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25733. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25734. var asset = sourceAssets_1[_i];
  25735. var move = true;
  25736. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25737. var keepAsset = keepAssets_1[_a];
  25738. if (asset === keepAsset) {
  25739. move = false;
  25740. break;
  25741. }
  25742. }
  25743. if (move) {
  25744. targetAssets.push(asset);
  25745. }
  25746. }
  25747. };
  25748. /**
  25749. * Removes all the assets contained in the scene and adds them to the container.
  25750. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25751. */
  25752. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25753. if (keepAssets === undefined) {
  25754. keepAssets = new KeepAssets();
  25755. }
  25756. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25757. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25758. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25759. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25760. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25761. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25762. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25763. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25764. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25765. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25766. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25767. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25768. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25769. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25770. this.removeAllFromScene();
  25771. };
  25772. return AssetContainer;
  25773. }());
  25774. BABYLON.AssetContainer = AssetContainer;
  25775. })(BABYLON || (BABYLON = {}));
  25776. //# sourceMappingURL=babylon.assetContainer.js.map
  25777. var BABYLON;
  25778. (function (BABYLON) {
  25779. var Buffer = /** @class */ (function () {
  25780. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25781. if (instanced === void 0) { instanced = false; }
  25782. if (engine instanceof BABYLON.Mesh) {
  25783. this._engine = engine.getScene().getEngine();
  25784. }
  25785. else {
  25786. this._engine = engine;
  25787. }
  25788. this._updatable = updatable;
  25789. this._instanced = instanced;
  25790. this._data = data;
  25791. this._strideSize = stride;
  25792. if (!postponeInternalCreation) {
  25793. this.create();
  25794. }
  25795. }
  25796. /**
  25797. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25798. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25799. * @param offset defines offset in the buffer (0 by default)
  25800. * @param size defines the size in floats of attributes (position is 3 for instance)
  25801. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25802. * @param instanced defines if the vertex buffer contains indexed data
  25803. * @returns the new vertex buffer
  25804. */
  25805. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25806. // a lot of these parameters are ignored as they are overriden by the buffer
  25807. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25808. };
  25809. // Properties
  25810. Buffer.prototype.isUpdatable = function () {
  25811. return this._updatable;
  25812. };
  25813. Buffer.prototype.getData = function () {
  25814. return this._data;
  25815. };
  25816. Buffer.prototype.getBuffer = function () {
  25817. return this._buffer;
  25818. };
  25819. Buffer.prototype.getStrideSize = function () {
  25820. return this._strideSize;
  25821. };
  25822. // public getIsInstanced(): boolean {
  25823. // return this._instanced;
  25824. // }
  25825. // public get instanceDivisor(): number {
  25826. // return this._instanceDivisor;
  25827. // }
  25828. // public set instanceDivisor(value: number) {
  25829. // this._instanceDivisor = value;
  25830. // if (value == 0) {
  25831. // this._instanced = false;
  25832. // } else {
  25833. // this._instanced = true;
  25834. // }
  25835. // }
  25836. // Methods
  25837. Buffer.prototype.create = function (data) {
  25838. if (data === void 0) { data = null; }
  25839. if (!data && this._buffer) {
  25840. return; // nothing to do
  25841. }
  25842. data = data || this._data;
  25843. if (!data) {
  25844. return;
  25845. }
  25846. if (!this._buffer) {
  25847. if (this._updatable) {
  25848. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25849. this._data = data;
  25850. }
  25851. else {
  25852. this._buffer = this._engine.createVertexBuffer(data);
  25853. }
  25854. }
  25855. else if (this._updatable) {
  25856. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25857. this._data = data;
  25858. }
  25859. };
  25860. Buffer.prototype._rebuild = function () {
  25861. this._buffer = null;
  25862. this.create(this._data);
  25863. };
  25864. Buffer.prototype.update = function (data) {
  25865. this.create(data);
  25866. };
  25867. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25868. if (!this._buffer) {
  25869. return;
  25870. }
  25871. if (this._updatable) {
  25872. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25873. this._data = null;
  25874. }
  25875. };
  25876. Buffer.prototype.dispose = function () {
  25877. if (!this._buffer) {
  25878. return;
  25879. }
  25880. if (this._engine._releaseBuffer(this._buffer)) {
  25881. this._buffer = null;
  25882. }
  25883. };
  25884. return Buffer;
  25885. }());
  25886. BABYLON.Buffer = Buffer;
  25887. })(BABYLON || (BABYLON = {}));
  25888. //# sourceMappingURL=babylon.buffer.js.map
  25889. var BABYLON;
  25890. (function (BABYLON) {
  25891. var VertexBuffer = /** @class */ (function () {
  25892. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25893. if (data instanceof BABYLON.Buffer) {
  25894. if (!stride) {
  25895. stride = data.getStrideSize();
  25896. }
  25897. this._buffer = data;
  25898. this._ownsBuffer = false;
  25899. }
  25900. else {
  25901. if (!stride) {
  25902. stride = VertexBuffer.DeduceStride(kind);
  25903. }
  25904. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25905. this._ownsBuffer = true;
  25906. }
  25907. this._stride = stride;
  25908. this._instanced = instanced !== undefined ? instanced : false;
  25909. this._instanceDivisor = instanced ? 1 : 0;
  25910. this._offset = offset ? offset : 0;
  25911. this._size = size ? size : stride;
  25912. this._kind = kind;
  25913. }
  25914. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25915. /**
  25916. * Gets or sets the instance divisor when in instanced mode
  25917. */
  25918. get: function () {
  25919. return this._instanceDivisor;
  25920. },
  25921. set: function (value) {
  25922. this._instanceDivisor = value;
  25923. if (value == 0) {
  25924. this._instanced = false;
  25925. }
  25926. else {
  25927. this._instanced = true;
  25928. }
  25929. },
  25930. enumerable: true,
  25931. configurable: true
  25932. });
  25933. VertexBuffer.prototype._rebuild = function () {
  25934. if (!this._buffer) {
  25935. return;
  25936. }
  25937. this._buffer._rebuild();
  25938. };
  25939. /**
  25940. * Returns the kind of the VertexBuffer (string).
  25941. */
  25942. VertexBuffer.prototype.getKind = function () {
  25943. return this._kind;
  25944. };
  25945. // Properties
  25946. /**
  25947. * Boolean : is the VertexBuffer updatable ?
  25948. */
  25949. VertexBuffer.prototype.isUpdatable = function () {
  25950. return this._buffer.isUpdatable();
  25951. };
  25952. /**
  25953. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25954. */
  25955. VertexBuffer.prototype.getData = function () {
  25956. return this._buffer.getData();
  25957. };
  25958. /**
  25959. * Returns the WebGLBuffer associated to the VertexBuffer.
  25960. */
  25961. VertexBuffer.prototype.getBuffer = function () {
  25962. return this._buffer.getBuffer();
  25963. };
  25964. /**
  25965. * Returns the stride of the VertexBuffer (integer).
  25966. */
  25967. VertexBuffer.prototype.getStrideSize = function () {
  25968. return this._stride;
  25969. };
  25970. /**
  25971. * Returns the offset (integer).
  25972. */
  25973. VertexBuffer.prototype.getOffset = function () {
  25974. return this._offset;
  25975. };
  25976. /**
  25977. * Returns the VertexBuffer total size (integer).
  25978. */
  25979. VertexBuffer.prototype.getSize = function () {
  25980. return this._size;
  25981. };
  25982. /**
  25983. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25984. */
  25985. VertexBuffer.prototype.getIsInstanced = function () {
  25986. return this._instanced;
  25987. };
  25988. /**
  25989. * Returns the instancing divisor, zero for non-instanced (integer).
  25990. */
  25991. VertexBuffer.prototype.getInstanceDivisor = function () {
  25992. return this._instanceDivisor;
  25993. };
  25994. // Methods
  25995. /**
  25996. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25997. * Returns the created WebGLBuffer.
  25998. */
  25999. VertexBuffer.prototype.create = function (data) {
  26000. return this._buffer.create(data);
  26001. };
  26002. /**
  26003. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26004. * This function will create a new buffer if the current one is not updatable
  26005. * Returns the updated WebGLBuffer.
  26006. */
  26007. VertexBuffer.prototype.update = function (data) {
  26008. return this._buffer.update(data);
  26009. };
  26010. /**
  26011. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26012. * Returns the directly updated WebGLBuffer.
  26013. */
  26014. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26015. return this._buffer.updateDirectly(data, offset);
  26016. };
  26017. /**
  26018. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26019. */
  26020. VertexBuffer.prototype.dispose = function () {
  26021. if (this._ownsBuffer) {
  26022. this._buffer.dispose();
  26023. }
  26024. };
  26025. Object.defineProperty(VertexBuffer, "PositionKind", {
  26026. get: function () {
  26027. return VertexBuffer._PositionKind;
  26028. },
  26029. enumerable: true,
  26030. configurable: true
  26031. });
  26032. Object.defineProperty(VertexBuffer, "NormalKind", {
  26033. get: function () {
  26034. return VertexBuffer._NormalKind;
  26035. },
  26036. enumerable: true,
  26037. configurable: true
  26038. });
  26039. Object.defineProperty(VertexBuffer, "TangentKind", {
  26040. get: function () {
  26041. return VertexBuffer._TangentKind;
  26042. },
  26043. enumerable: true,
  26044. configurable: true
  26045. });
  26046. Object.defineProperty(VertexBuffer, "UVKind", {
  26047. get: function () {
  26048. return VertexBuffer._UVKind;
  26049. },
  26050. enumerable: true,
  26051. configurable: true
  26052. });
  26053. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26054. get: function () {
  26055. return VertexBuffer._UV2Kind;
  26056. },
  26057. enumerable: true,
  26058. configurable: true
  26059. });
  26060. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26061. get: function () {
  26062. return VertexBuffer._UV3Kind;
  26063. },
  26064. enumerable: true,
  26065. configurable: true
  26066. });
  26067. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26068. get: function () {
  26069. return VertexBuffer._UV4Kind;
  26070. },
  26071. enumerable: true,
  26072. configurable: true
  26073. });
  26074. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26075. get: function () {
  26076. return VertexBuffer._UV5Kind;
  26077. },
  26078. enumerable: true,
  26079. configurable: true
  26080. });
  26081. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26082. get: function () {
  26083. return VertexBuffer._UV6Kind;
  26084. },
  26085. enumerable: true,
  26086. configurable: true
  26087. });
  26088. Object.defineProperty(VertexBuffer, "ColorKind", {
  26089. get: function () {
  26090. return VertexBuffer._ColorKind;
  26091. },
  26092. enumerable: true,
  26093. configurable: true
  26094. });
  26095. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26096. get: function () {
  26097. return VertexBuffer._MatricesIndicesKind;
  26098. },
  26099. enumerable: true,
  26100. configurable: true
  26101. });
  26102. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26103. get: function () {
  26104. return VertexBuffer._MatricesWeightsKind;
  26105. },
  26106. enumerable: true,
  26107. configurable: true
  26108. });
  26109. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26110. get: function () {
  26111. return VertexBuffer._MatricesIndicesExtraKind;
  26112. },
  26113. enumerable: true,
  26114. configurable: true
  26115. });
  26116. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26117. get: function () {
  26118. return VertexBuffer._MatricesWeightsExtraKind;
  26119. },
  26120. enumerable: true,
  26121. configurable: true
  26122. });
  26123. /**
  26124. * Deduces the stride given a kind.
  26125. * @param kind The kind string to deduce
  26126. * @returns The deduced stride
  26127. */
  26128. VertexBuffer.DeduceStride = function (kind) {
  26129. switch (kind) {
  26130. case VertexBuffer.UVKind:
  26131. case VertexBuffer.UV2Kind:
  26132. case VertexBuffer.UV3Kind:
  26133. case VertexBuffer.UV4Kind:
  26134. case VertexBuffer.UV5Kind:
  26135. case VertexBuffer.UV6Kind:
  26136. return 2;
  26137. case VertexBuffer.NormalKind:
  26138. case VertexBuffer.PositionKind:
  26139. return 3;
  26140. case VertexBuffer.ColorKind:
  26141. case VertexBuffer.MatricesIndicesKind:
  26142. case VertexBuffer.MatricesIndicesExtraKind:
  26143. case VertexBuffer.MatricesWeightsKind:
  26144. case VertexBuffer.MatricesWeightsExtraKind:
  26145. case VertexBuffer.TangentKind:
  26146. return 4;
  26147. default:
  26148. throw new Error("Invalid kind '" + kind + "'");
  26149. }
  26150. };
  26151. // Enums
  26152. VertexBuffer._PositionKind = "position";
  26153. VertexBuffer._NormalKind = "normal";
  26154. VertexBuffer._TangentKind = "tangent";
  26155. VertexBuffer._UVKind = "uv";
  26156. VertexBuffer._UV2Kind = "uv2";
  26157. VertexBuffer._UV3Kind = "uv3";
  26158. VertexBuffer._UV4Kind = "uv4";
  26159. VertexBuffer._UV5Kind = "uv5";
  26160. VertexBuffer._UV6Kind = "uv6";
  26161. VertexBuffer._ColorKind = "color";
  26162. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26163. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26164. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26165. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26166. return VertexBuffer;
  26167. }());
  26168. BABYLON.VertexBuffer = VertexBuffer;
  26169. })(BABYLON || (BABYLON = {}));
  26170. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26171. var BABYLON;
  26172. (function (BABYLON) {
  26173. /**
  26174. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26175. */
  26176. var DummyInternalTextureTracker = /** @class */ (function () {
  26177. function DummyInternalTextureTracker() {
  26178. /**
  26179. * Gets or set the previous tracker in the list
  26180. */
  26181. this.previous = null;
  26182. /**
  26183. * Gets or set the next tracker in the list
  26184. */
  26185. this.next = null;
  26186. }
  26187. return DummyInternalTextureTracker;
  26188. }());
  26189. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26190. })(BABYLON || (BABYLON = {}));
  26191. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26192. var BABYLON;
  26193. (function (BABYLON) {
  26194. /**
  26195. * Class used to store data associated with WebGL texture data for the engine
  26196. * This class should not be used directly
  26197. */
  26198. var InternalTexture = /** @class */ (function () {
  26199. /**
  26200. * Creates a new InternalTexture
  26201. * @param engine defines the engine to use
  26202. * @param dataSource defines the type of data that will be used
  26203. */
  26204. function InternalTexture(engine, dataSource) {
  26205. /**
  26206. * Observable called when the texture is loaded
  26207. */
  26208. this.onLoadedObservable = new BABYLON.Observable();
  26209. /**
  26210. * Gets or set the previous tracker in the list
  26211. */
  26212. this.previous = null;
  26213. /**
  26214. * Gets or set the next tracker in the list
  26215. */
  26216. this.next = null;
  26217. // Private
  26218. /** @ignore */
  26219. this._initialSlot = -1;
  26220. /** @ignore */
  26221. this._designatedSlot = -1;
  26222. /** @ignore */
  26223. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26224. /** @ignore */
  26225. this._comparisonFunction = 0;
  26226. /** @ignore */
  26227. this._references = 1;
  26228. this._engine = engine;
  26229. this._dataSource = dataSource;
  26230. this._webGLTexture = engine._createTexture();
  26231. }
  26232. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26233. /**
  26234. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26235. */
  26236. get: function () {
  26237. return this._dataSource;
  26238. },
  26239. enumerable: true,
  26240. configurable: true
  26241. });
  26242. /**
  26243. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26244. */
  26245. InternalTexture.prototype.incrementReferences = function () {
  26246. this._references++;
  26247. };
  26248. /**
  26249. * Change the size of the texture (not the size of the content)
  26250. * @param width defines the new width
  26251. * @param height defines the new height
  26252. * @param depth defines the new depth (1 by default)
  26253. */
  26254. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26255. if (depth === void 0) { depth = 1; }
  26256. this.width = width;
  26257. this.height = height;
  26258. this.depth = depth;
  26259. this.baseWidth = width;
  26260. this.baseHeight = height;
  26261. this.baseDepth = depth;
  26262. this._size = width * height * depth;
  26263. };
  26264. /** @ignore */
  26265. InternalTexture.prototype._rebuild = function () {
  26266. var _this = this;
  26267. var proxy;
  26268. this.isReady = false;
  26269. this._cachedCoordinatesMode = null;
  26270. this._cachedWrapU = null;
  26271. this._cachedWrapV = null;
  26272. this._cachedAnisotropicFilteringLevel = null;
  26273. switch (this._dataSource) {
  26274. case InternalTexture.DATASOURCE_TEMP:
  26275. return;
  26276. case InternalTexture.DATASOURCE_URL:
  26277. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26278. _this.isReady = true;
  26279. }, null, this._buffer, undefined, this.format);
  26280. proxy._swapAndDie(this);
  26281. return;
  26282. case InternalTexture.DATASOURCE_RAW:
  26283. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26284. proxy._swapAndDie(this);
  26285. this.isReady = true;
  26286. return;
  26287. case InternalTexture.DATASOURCE_RAW3D:
  26288. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26289. proxy._swapAndDie(this);
  26290. this.isReady = true;
  26291. return;
  26292. case InternalTexture.DATASOURCE_DYNAMIC:
  26293. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26294. proxy._swapAndDie(this);
  26295. // The engine will make sure to update content so no need to flag it as isReady = true
  26296. return;
  26297. case InternalTexture.DATASOURCE_RENDERTARGET:
  26298. var options = new BABYLON.RenderTargetCreationOptions();
  26299. options.generateDepthBuffer = this._generateDepthBuffer;
  26300. options.generateMipMaps = this.generateMipMaps;
  26301. options.generateStencilBuffer = this._generateStencilBuffer;
  26302. options.samplingMode = this.samplingMode;
  26303. options.type = this.type;
  26304. if (this.isCube) {
  26305. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26306. }
  26307. else {
  26308. var size = {
  26309. width: this.width,
  26310. height: this.height
  26311. };
  26312. proxy = this._engine.createRenderTargetTexture(size, options);
  26313. }
  26314. proxy._swapAndDie(this);
  26315. this.isReady = true;
  26316. return;
  26317. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26318. var depthTextureOptions = {
  26319. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26320. comparisonFunction: this._comparisonFunction,
  26321. generateStencil: this._generateStencilBuffer,
  26322. };
  26323. if (this.isCube) {
  26324. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26325. }
  26326. else {
  26327. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26328. }
  26329. proxy._swapAndDie(this);
  26330. this.isReady = true;
  26331. return;
  26332. case InternalTexture.DATASOURCE_CUBE:
  26333. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26334. _this.isReady = true;
  26335. }, null, this.format, this._extension);
  26336. proxy._swapAndDie(this);
  26337. return;
  26338. case InternalTexture.DATASOURCE_CUBERAW:
  26339. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26340. proxy._swapAndDie(this);
  26341. this.isReady = true;
  26342. return;
  26343. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26344. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26345. if (proxy) {
  26346. proxy._swapAndDie(_this);
  26347. }
  26348. _this.isReady = true;
  26349. }, null, this.format, this._extension);
  26350. return;
  26351. }
  26352. };
  26353. InternalTexture.prototype._swapAndDie = function (target) {
  26354. target._webGLTexture = this._webGLTexture;
  26355. if (this._framebuffer) {
  26356. target._framebuffer = this._framebuffer;
  26357. }
  26358. if (this._depthStencilBuffer) {
  26359. target._depthStencilBuffer = this._depthStencilBuffer;
  26360. }
  26361. if (this._lodTextureHigh) {
  26362. if (target._lodTextureHigh) {
  26363. target._lodTextureHigh.dispose();
  26364. }
  26365. target._lodTextureHigh = this._lodTextureHigh;
  26366. }
  26367. if (this._lodTextureMid) {
  26368. if (target._lodTextureMid) {
  26369. target._lodTextureMid.dispose();
  26370. }
  26371. target._lodTextureMid = this._lodTextureMid;
  26372. }
  26373. if (this._lodTextureLow) {
  26374. if (target._lodTextureLow) {
  26375. target._lodTextureLow.dispose();
  26376. }
  26377. target._lodTextureLow = this._lodTextureLow;
  26378. }
  26379. var cache = this._engine.getLoadedTexturesCache();
  26380. var index = cache.indexOf(this);
  26381. if (index !== -1) {
  26382. cache.splice(index, 1);
  26383. }
  26384. };
  26385. /**
  26386. * Dispose the current allocated resources
  26387. */
  26388. InternalTexture.prototype.dispose = function () {
  26389. if (!this._webGLTexture) {
  26390. return;
  26391. }
  26392. this._references--;
  26393. if (this._references === 0) {
  26394. this._engine._releaseTexture(this);
  26395. this._webGLTexture = null;
  26396. this.previous = null;
  26397. this.next = null;
  26398. }
  26399. };
  26400. /**
  26401. * The source of the texture data is unknown
  26402. */
  26403. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26404. /**
  26405. * Texture data comes from an URL
  26406. */
  26407. InternalTexture.DATASOURCE_URL = 1;
  26408. /**
  26409. * Texture data is only used for temporary storage
  26410. */
  26411. InternalTexture.DATASOURCE_TEMP = 2;
  26412. /**
  26413. * Texture data comes from raw data (ArrayBuffer)
  26414. */
  26415. InternalTexture.DATASOURCE_RAW = 3;
  26416. /**
  26417. * Texture content is dynamic (video or dynamic texture)
  26418. */
  26419. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26420. /**
  26421. * Texture content is generated by rendering to it
  26422. */
  26423. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26424. /**
  26425. * Texture content is part of a multi render target process
  26426. */
  26427. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26428. /**
  26429. * Texture data comes from a cube data file
  26430. */
  26431. InternalTexture.DATASOURCE_CUBE = 7;
  26432. /**
  26433. * Texture data comes from a raw cube data
  26434. */
  26435. InternalTexture.DATASOURCE_CUBERAW = 8;
  26436. /**
  26437. * Texture data come from a prefiltered cube data file
  26438. */
  26439. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26440. /**
  26441. * Texture content is raw 3D data
  26442. */
  26443. InternalTexture.DATASOURCE_RAW3D = 10;
  26444. /**
  26445. * Texture content is a depth texture
  26446. */
  26447. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26448. return InternalTexture;
  26449. }());
  26450. BABYLON.InternalTexture = InternalTexture;
  26451. })(BABYLON || (BABYLON = {}));
  26452. //# sourceMappingURL=babylon.internalTexture.js.map
  26453. var BABYLON;
  26454. (function (BABYLON) {
  26455. var BaseTexture = /** @class */ (function () {
  26456. function BaseTexture(scene) {
  26457. this._hasAlpha = false;
  26458. this.getAlphaFromRGB = false;
  26459. this.level = 1;
  26460. this.coordinatesIndex = 0;
  26461. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26462. /**
  26463. * | Value | Type | Description |
  26464. * | ----- | ------------------ | ----------- |
  26465. * | 0 | CLAMP_ADDRESSMODE | |
  26466. * | 1 | WRAP_ADDRESSMODE | |
  26467. * | 2 | MIRROR_ADDRESSMODE | |
  26468. */
  26469. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26470. /**
  26471. * | Value | Type | Description |
  26472. * | ----- | ------------------ | ----------- |
  26473. * | 0 | CLAMP_ADDRESSMODE | |
  26474. * | 1 | WRAP_ADDRESSMODE | |
  26475. * | 2 | MIRROR_ADDRESSMODE | |
  26476. */
  26477. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26478. /**
  26479. * | Value | Type | Description |
  26480. * | ----- | ------------------ | ----------- |
  26481. * | 0 | CLAMP_ADDRESSMODE | |
  26482. * | 1 | WRAP_ADDRESSMODE | |
  26483. * | 2 | MIRROR_ADDRESSMODE | |
  26484. */
  26485. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26486. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26487. this.isCube = false;
  26488. this.is3D = false;
  26489. this.gammaSpace = true;
  26490. this.invertZ = false;
  26491. this.lodLevelInAlpha = false;
  26492. this.lodGenerationOffset = 0.0;
  26493. this.lodGenerationScale = 0.8;
  26494. this.isRenderTarget = false;
  26495. this.animations = new Array();
  26496. /**
  26497. * An event triggered when the texture is disposed.
  26498. * @type {BABYLON.Observable}
  26499. */
  26500. this.onDisposeObservable = new BABYLON.Observable();
  26501. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26502. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26503. if (this._scene) {
  26504. this._scene.textures.push(this);
  26505. }
  26506. this._uid = null;
  26507. }
  26508. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26509. get: function () {
  26510. return this._hasAlpha;
  26511. },
  26512. set: function (value) {
  26513. if (this._hasAlpha === value) {
  26514. return;
  26515. }
  26516. this._hasAlpha = value;
  26517. if (this._scene) {
  26518. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26519. }
  26520. },
  26521. enumerable: true,
  26522. configurable: true
  26523. });
  26524. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26525. get: function () {
  26526. return this._coordinatesMode;
  26527. },
  26528. /**
  26529. * How a texture is mapped.
  26530. *
  26531. * | Value | Type | Description |
  26532. * | ----- | ----------------------------------- | ----------- |
  26533. * | 0 | EXPLICIT_MODE | |
  26534. * | 1 | SPHERICAL_MODE | |
  26535. * | 2 | PLANAR_MODE | |
  26536. * | 3 | CUBIC_MODE | |
  26537. * | 4 | PROJECTION_MODE | |
  26538. * | 5 | SKYBOX_MODE | |
  26539. * | 6 | INVCUBIC_MODE | |
  26540. * | 7 | EQUIRECTANGULAR_MODE | |
  26541. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26542. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26543. */
  26544. set: function (value) {
  26545. if (this._coordinatesMode === value) {
  26546. return;
  26547. }
  26548. this._coordinatesMode = value;
  26549. if (this._scene) {
  26550. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26551. }
  26552. },
  26553. enumerable: true,
  26554. configurable: true
  26555. });
  26556. Object.defineProperty(BaseTexture.prototype, "uid", {
  26557. get: function () {
  26558. if (!this._uid) {
  26559. this._uid = BABYLON.Tools.RandomId();
  26560. }
  26561. return this._uid;
  26562. },
  26563. enumerable: true,
  26564. configurable: true
  26565. });
  26566. BaseTexture.prototype.toString = function () {
  26567. return this.name;
  26568. };
  26569. BaseTexture.prototype.getClassName = function () {
  26570. return "BaseTexture";
  26571. };
  26572. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26573. set: function (callback) {
  26574. if (this._onDisposeObserver) {
  26575. this.onDisposeObservable.remove(this._onDisposeObserver);
  26576. }
  26577. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26578. },
  26579. enumerable: true,
  26580. configurable: true
  26581. });
  26582. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26583. get: function () {
  26584. return true;
  26585. },
  26586. enumerable: true,
  26587. configurable: true
  26588. });
  26589. BaseTexture.prototype.getScene = function () {
  26590. return this._scene;
  26591. };
  26592. BaseTexture.prototype.getTextureMatrix = function () {
  26593. return BABYLON.Matrix.IdentityReadOnly;
  26594. };
  26595. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26596. return BABYLON.Matrix.IdentityReadOnly;
  26597. };
  26598. BaseTexture.prototype.getInternalTexture = function () {
  26599. return this._texture;
  26600. };
  26601. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26602. return !this.isBlocking || this.isReady();
  26603. };
  26604. BaseTexture.prototype.isReady = function () {
  26605. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26606. this.delayLoad();
  26607. return false;
  26608. }
  26609. if (this._texture) {
  26610. return this._texture.isReady;
  26611. }
  26612. return false;
  26613. };
  26614. BaseTexture.prototype.getSize = function () {
  26615. if (this._texture && this._texture.width) {
  26616. return new BABYLON.Size(this._texture.width, this._texture.height);
  26617. }
  26618. if (this._texture && this._texture._size) {
  26619. return new BABYLON.Size(this._texture._size, this._texture._size);
  26620. }
  26621. return BABYLON.Size.Zero();
  26622. };
  26623. BaseTexture.prototype.getBaseSize = function () {
  26624. if (!this.isReady() || !this._texture)
  26625. return BABYLON.Size.Zero();
  26626. if (this._texture._size) {
  26627. return new BABYLON.Size(this._texture._size, this._texture._size);
  26628. }
  26629. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26630. };
  26631. BaseTexture.prototype.scale = function (ratio) {
  26632. };
  26633. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26634. get: function () {
  26635. return false;
  26636. },
  26637. enumerable: true,
  26638. configurable: true
  26639. });
  26640. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26641. if (!this._scene) {
  26642. return null;
  26643. }
  26644. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26645. for (var index = 0; index < texturesCache.length; index++) {
  26646. var texturesCacheEntry = texturesCache[index];
  26647. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26648. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26649. texturesCacheEntry.incrementReferences();
  26650. return texturesCacheEntry;
  26651. }
  26652. }
  26653. }
  26654. return null;
  26655. };
  26656. BaseTexture.prototype._rebuild = function () {
  26657. };
  26658. BaseTexture.prototype.delayLoad = function () {
  26659. };
  26660. BaseTexture.prototype.clone = function () {
  26661. return null;
  26662. };
  26663. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26664. get: function () {
  26665. if (!this._texture) {
  26666. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26667. }
  26668. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26669. },
  26670. enumerable: true,
  26671. configurable: true
  26672. });
  26673. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26674. get: function () {
  26675. if (!this._texture) {
  26676. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26677. }
  26678. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26679. },
  26680. enumerable: true,
  26681. configurable: true
  26682. });
  26683. BaseTexture.prototype.readPixels = function (faceIndex) {
  26684. if (faceIndex === void 0) { faceIndex = 0; }
  26685. if (!this._texture) {
  26686. return null;
  26687. }
  26688. var size = this.getSize();
  26689. var scene = this.getScene();
  26690. if (!scene) {
  26691. return null;
  26692. }
  26693. var engine = scene.getEngine();
  26694. if (this._texture.isCube) {
  26695. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26696. }
  26697. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26698. };
  26699. BaseTexture.prototype.releaseInternalTexture = function () {
  26700. if (this._texture) {
  26701. this._texture.dispose();
  26702. this._texture = null;
  26703. }
  26704. };
  26705. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26706. get: function () {
  26707. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26708. return null;
  26709. }
  26710. if (!this._texture._sphericalPolynomial) {
  26711. this._texture._sphericalPolynomial =
  26712. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26713. }
  26714. return this._texture._sphericalPolynomial;
  26715. },
  26716. set: function (value) {
  26717. if (this._texture) {
  26718. this._texture._sphericalPolynomial = value;
  26719. }
  26720. },
  26721. enumerable: true,
  26722. configurable: true
  26723. });
  26724. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26725. get: function () {
  26726. if (this._texture) {
  26727. return this._texture._lodTextureHigh;
  26728. }
  26729. return null;
  26730. },
  26731. enumerable: true,
  26732. configurable: true
  26733. });
  26734. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26735. get: function () {
  26736. if (this._texture) {
  26737. return this._texture._lodTextureMid;
  26738. }
  26739. return null;
  26740. },
  26741. enumerable: true,
  26742. configurable: true
  26743. });
  26744. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26745. get: function () {
  26746. if (this._texture) {
  26747. return this._texture._lodTextureLow;
  26748. }
  26749. return null;
  26750. },
  26751. enumerable: true,
  26752. configurable: true
  26753. });
  26754. BaseTexture.prototype.dispose = function () {
  26755. if (!this._scene) {
  26756. return;
  26757. }
  26758. // Animations
  26759. this._scene.stopAnimation(this);
  26760. // Remove from scene
  26761. this._scene._removePendingData(this);
  26762. var index = this._scene.textures.indexOf(this);
  26763. if (index >= 0) {
  26764. this._scene.textures.splice(index, 1);
  26765. }
  26766. if (this._texture === undefined) {
  26767. return;
  26768. }
  26769. // Release
  26770. this.releaseInternalTexture();
  26771. // Callback
  26772. this.onDisposeObservable.notifyObservers(this);
  26773. this.onDisposeObservable.clear();
  26774. };
  26775. BaseTexture.prototype.serialize = function () {
  26776. if (!this.name) {
  26777. return null;
  26778. }
  26779. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26780. // Animations
  26781. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26782. return serializationObject;
  26783. };
  26784. BaseTexture.WhenAllReady = function (textures, callback) {
  26785. var numRemaining = textures.length;
  26786. if (numRemaining === 0) {
  26787. callback();
  26788. return;
  26789. }
  26790. var _loop_1 = function () {
  26791. texture = textures[i];
  26792. if (texture.isReady()) {
  26793. if (--numRemaining === 0) {
  26794. callback();
  26795. }
  26796. }
  26797. else {
  26798. onLoadObservable = texture.onLoadObservable;
  26799. var onLoadCallback_1 = function () {
  26800. onLoadObservable.removeCallback(onLoadCallback_1);
  26801. if (--numRemaining === 0) {
  26802. callback();
  26803. }
  26804. };
  26805. onLoadObservable.add(onLoadCallback_1);
  26806. }
  26807. };
  26808. var texture, onLoadObservable;
  26809. for (var i = 0; i < textures.length; i++) {
  26810. _loop_1();
  26811. }
  26812. };
  26813. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26814. __decorate([
  26815. BABYLON.serialize()
  26816. ], BaseTexture.prototype, "name", void 0);
  26817. __decorate([
  26818. BABYLON.serialize("hasAlpha")
  26819. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26820. __decorate([
  26821. BABYLON.serialize()
  26822. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26823. __decorate([
  26824. BABYLON.serialize()
  26825. ], BaseTexture.prototype, "level", void 0);
  26826. __decorate([
  26827. BABYLON.serialize()
  26828. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26829. __decorate([
  26830. BABYLON.serialize("coordinatesMode")
  26831. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26832. __decorate([
  26833. BABYLON.serialize()
  26834. ], BaseTexture.prototype, "wrapU", void 0);
  26835. __decorate([
  26836. BABYLON.serialize()
  26837. ], BaseTexture.prototype, "wrapV", void 0);
  26838. __decorate([
  26839. BABYLON.serialize()
  26840. ], BaseTexture.prototype, "wrapR", void 0);
  26841. __decorate([
  26842. BABYLON.serialize()
  26843. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26844. __decorate([
  26845. BABYLON.serialize()
  26846. ], BaseTexture.prototype, "isCube", void 0);
  26847. __decorate([
  26848. BABYLON.serialize()
  26849. ], BaseTexture.prototype, "is3D", void 0);
  26850. __decorate([
  26851. BABYLON.serialize()
  26852. ], BaseTexture.prototype, "gammaSpace", void 0);
  26853. __decorate([
  26854. BABYLON.serialize()
  26855. ], BaseTexture.prototype, "invertZ", void 0);
  26856. __decorate([
  26857. BABYLON.serialize()
  26858. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26859. __decorate([
  26860. BABYLON.serialize()
  26861. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26862. __decorate([
  26863. BABYLON.serialize()
  26864. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26865. __decorate([
  26866. BABYLON.serialize()
  26867. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26868. return BaseTexture;
  26869. }());
  26870. BABYLON.BaseTexture = BaseTexture;
  26871. })(BABYLON || (BABYLON = {}));
  26872. //# sourceMappingURL=babylon.baseTexture.js.map
  26873. var BABYLON;
  26874. (function (BABYLON) {
  26875. var Texture = /** @class */ (function (_super) {
  26876. __extends(Texture, _super);
  26877. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26878. if (noMipmap === void 0) { noMipmap = false; }
  26879. if (invertY === void 0) { invertY = true; }
  26880. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26881. if (onLoad === void 0) { onLoad = null; }
  26882. if (onError === void 0) { onError = null; }
  26883. if (buffer === void 0) { buffer = null; }
  26884. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26885. var _this = _super.call(this, scene) || this;
  26886. _this.uOffset = 0;
  26887. _this.vOffset = 0;
  26888. _this.uScale = 1.0;
  26889. _this.vScale = 1.0;
  26890. _this.uAng = 0;
  26891. _this.vAng = 0;
  26892. _this.wAng = 0;
  26893. _this._isBlocking = true;
  26894. _this.name = url || "";
  26895. _this.url = url;
  26896. _this._noMipmap = noMipmap;
  26897. _this._invertY = invertY;
  26898. _this._samplingMode = samplingMode;
  26899. _this._buffer = buffer;
  26900. _this._deleteBuffer = deleteBuffer;
  26901. if (format) {
  26902. _this._format = format;
  26903. }
  26904. scene = _this.getScene();
  26905. if (!scene) {
  26906. return _this;
  26907. }
  26908. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26909. var load = function () {
  26910. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26911. _this.onLoadObservable.notifyObservers(_this);
  26912. }
  26913. if (onLoad) {
  26914. onLoad();
  26915. }
  26916. if (!_this.isBlocking && scene) {
  26917. scene.resetCachedMaterial();
  26918. }
  26919. };
  26920. if (!_this.url) {
  26921. _this._delayedOnLoad = load;
  26922. _this._delayedOnError = onError;
  26923. return _this;
  26924. }
  26925. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26926. if (!_this._texture) {
  26927. if (!scene.useDelayedTextureLoading) {
  26928. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26929. if (deleteBuffer) {
  26930. delete _this._buffer;
  26931. }
  26932. }
  26933. else {
  26934. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26935. _this._delayedOnLoad = load;
  26936. _this._delayedOnError = onError;
  26937. }
  26938. }
  26939. else {
  26940. if (_this._texture.isReady) {
  26941. BABYLON.Tools.SetImmediate(function () { return load(); });
  26942. }
  26943. else {
  26944. _this._texture.onLoadedObservable.add(load);
  26945. }
  26946. }
  26947. return _this;
  26948. }
  26949. Object.defineProperty(Texture.prototype, "noMipmap", {
  26950. get: function () {
  26951. return this._noMipmap;
  26952. },
  26953. enumerable: true,
  26954. configurable: true
  26955. });
  26956. Object.defineProperty(Texture.prototype, "isBlocking", {
  26957. get: function () {
  26958. return this._isBlocking;
  26959. },
  26960. set: function (value) {
  26961. this._isBlocking = value;
  26962. },
  26963. enumerable: true,
  26964. configurable: true
  26965. });
  26966. Object.defineProperty(Texture.prototype, "samplingMode", {
  26967. get: function () {
  26968. return this._samplingMode;
  26969. },
  26970. enumerable: true,
  26971. configurable: true
  26972. });
  26973. Texture.prototype.updateURL = function (url) {
  26974. this.url = url;
  26975. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26976. this.delayLoad();
  26977. };
  26978. Texture.prototype.delayLoad = function () {
  26979. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26980. return;
  26981. }
  26982. var scene = this.getScene();
  26983. if (!scene) {
  26984. return;
  26985. }
  26986. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26987. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26988. if (!this._texture) {
  26989. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26990. if (this._deleteBuffer) {
  26991. delete this._buffer;
  26992. }
  26993. }
  26994. else {
  26995. if (this._delayedOnLoad) {
  26996. if (this._texture.isReady) {
  26997. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26998. }
  26999. else {
  27000. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27001. }
  27002. }
  27003. }
  27004. this._delayedOnLoad = null;
  27005. this._delayedOnError = null;
  27006. };
  27007. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27008. if (!this._texture) {
  27009. return;
  27010. }
  27011. var scene = this.getScene();
  27012. if (!scene) {
  27013. return;
  27014. }
  27015. this._samplingMode = samplingMode;
  27016. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27017. };
  27018. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27019. x *= this.uScale;
  27020. y *= this.vScale;
  27021. x -= 0.5 * this.uScale;
  27022. y -= 0.5 * this.vScale;
  27023. z -= 0.5;
  27024. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27025. t.x += 0.5 * this.uScale + this.uOffset;
  27026. t.y += 0.5 * this.vScale + this.vOffset;
  27027. t.z += 0.5;
  27028. };
  27029. Texture.prototype.getTextureMatrix = function () {
  27030. var _this = this;
  27031. if (this.uOffset === this._cachedUOffset &&
  27032. this.vOffset === this._cachedVOffset &&
  27033. this.uScale === this._cachedUScale &&
  27034. this.vScale === this._cachedVScale &&
  27035. this.uAng === this._cachedUAng &&
  27036. this.vAng === this._cachedVAng &&
  27037. this.wAng === this._cachedWAng) {
  27038. return this._cachedTextureMatrix;
  27039. }
  27040. this._cachedUOffset = this.uOffset;
  27041. this._cachedVOffset = this.vOffset;
  27042. this._cachedUScale = this.uScale;
  27043. this._cachedVScale = this.vScale;
  27044. this._cachedUAng = this.uAng;
  27045. this._cachedVAng = this.vAng;
  27046. this._cachedWAng = this.wAng;
  27047. if (!this._cachedTextureMatrix) {
  27048. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27049. this._rowGenerationMatrix = new BABYLON.Matrix();
  27050. this._t0 = BABYLON.Vector3.Zero();
  27051. this._t1 = BABYLON.Vector3.Zero();
  27052. this._t2 = BABYLON.Vector3.Zero();
  27053. }
  27054. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27055. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27056. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27057. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27058. this._t1.subtractInPlace(this._t0);
  27059. this._t2.subtractInPlace(this._t0);
  27060. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27061. this._cachedTextureMatrix.m[0] = this._t1.x;
  27062. this._cachedTextureMatrix.m[1] = this._t1.y;
  27063. this._cachedTextureMatrix.m[2] = this._t1.z;
  27064. this._cachedTextureMatrix.m[4] = this._t2.x;
  27065. this._cachedTextureMatrix.m[5] = this._t2.y;
  27066. this._cachedTextureMatrix.m[6] = this._t2.z;
  27067. this._cachedTextureMatrix.m[8] = this._t0.x;
  27068. this._cachedTextureMatrix.m[9] = this._t0.y;
  27069. this._cachedTextureMatrix.m[10] = this._t0.z;
  27070. var scene = this.getScene();
  27071. if (!scene) {
  27072. return this._cachedTextureMatrix;
  27073. }
  27074. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27075. return mat.hasTexture(_this);
  27076. });
  27077. return this._cachedTextureMatrix;
  27078. };
  27079. Texture.prototype.getReflectionTextureMatrix = function () {
  27080. var _this = this;
  27081. var scene = this.getScene();
  27082. if (!scene) {
  27083. return this._cachedTextureMatrix;
  27084. }
  27085. if (this.uOffset === this._cachedUOffset &&
  27086. this.vOffset === this._cachedVOffset &&
  27087. this.uScale === this._cachedUScale &&
  27088. this.vScale === this._cachedVScale &&
  27089. this.coordinatesMode === this._cachedCoordinatesMode) {
  27090. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27091. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27092. return this._cachedTextureMatrix;
  27093. }
  27094. }
  27095. else {
  27096. return this._cachedTextureMatrix;
  27097. }
  27098. }
  27099. if (!this._cachedTextureMatrix) {
  27100. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27101. }
  27102. if (!this._projectionModeMatrix) {
  27103. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27104. }
  27105. this._cachedUOffset = this.uOffset;
  27106. this._cachedVOffset = this.vOffset;
  27107. this._cachedUScale = this.uScale;
  27108. this._cachedVScale = this.vScale;
  27109. this._cachedCoordinatesMode = this.coordinatesMode;
  27110. switch (this.coordinatesMode) {
  27111. case Texture.PLANAR_MODE:
  27112. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27113. this._cachedTextureMatrix[0] = this.uScale;
  27114. this._cachedTextureMatrix[5] = this.vScale;
  27115. this._cachedTextureMatrix[12] = this.uOffset;
  27116. this._cachedTextureMatrix[13] = this.vOffset;
  27117. break;
  27118. case Texture.PROJECTION_MODE:
  27119. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27120. this._projectionModeMatrix.m[0] = 0.5;
  27121. this._projectionModeMatrix.m[5] = -0.5;
  27122. this._projectionModeMatrix.m[10] = 0.0;
  27123. this._projectionModeMatrix.m[12] = 0.5;
  27124. this._projectionModeMatrix.m[13] = 0.5;
  27125. this._projectionModeMatrix.m[14] = 1.0;
  27126. this._projectionModeMatrix.m[15] = 1.0;
  27127. var projectionMatrix = scene.getProjectionMatrix();
  27128. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27129. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27130. break;
  27131. default:
  27132. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27133. break;
  27134. }
  27135. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27136. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27137. });
  27138. return this._cachedTextureMatrix;
  27139. };
  27140. Texture.prototype.clone = function () {
  27141. var _this = this;
  27142. return BABYLON.SerializationHelper.Clone(function () {
  27143. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27144. }, this);
  27145. };
  27146. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27147. get: function () {
  27148. if (!this._onLoadObservable) {
  27149. this._onLoadObservable = new BABYLON.Observable();
  27150. }
  27151. return this._onLoadObservable;
  27152. },
  27153. enumerable: true,
  27154. configurable: true
  27155. });
  27156. Texture.prototype.serialize = function () {
  27157. var serializationObject = _super.prototype.serialize.call(this);
  27158. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27159. serializationObject.base64String = this._buffer;
  27160. serializationObject.name = serializationObject.name.replace("data:", "");
  27161. }
  27162. return serializationObject;
  27163. };
  27164. Texture.prototype.getClassName = function () {
  27165. return "Texture";
  27166. };
  27167. Texture.prototype.dispose = function () {
  27168. _super.prototype.dispose.call(this);
  27169. if (this.onLoadObservable) {
  27170. this.onLoadObservable.clear();
  27171. this._onLoadObservable = null;
  27172. }
  27173. this._delayedOnLoad = null;
  27174. this._delayedOnError = null;
  27175. };
  27176. // Statics
  27177. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27178. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27179. if (onLoad === void 0) { onLoad = null; }
  27180. if (onError === void 0) { onError = null; }
  27181. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27182. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27183. };
  27184. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27185. if (parsedTexture.customType) {
  27186. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27187. // Update Sampling Mode
  27188. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27189. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27190. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27191. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27192. }
  27193. }
  27194. return parsedCustomTexture;
  27195. }
  27196. if (parsedTexture.isCube) {
  27197. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27198. }
  27199. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27200. return null;
  27201. }
  27202. var texture = BABYLON.SerializationHelper.Parse(function () {
  27203. var generateMipMaps = true;
  27204. if (parsedTexture.noMipmap) {
  27205. generateMipMaps = false;
  27206. }
  27207. if (parsedTexture.mirrorPlane) {
  27208. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27209. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27210. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27211. return mirrorTexture;
  27212. }
  27213. else if (parsedTexture.isRenderTarget) {
  27214. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27215. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27216. return renderTargetTexture;
  27217. }
  27218. else {
  27219. var texture;
  27220. if (parsedTexture.base64String) {
  27221. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27222. }
  27223. else {
  27224. var url = rootUrl + parsedTexture.name;
  27225. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27226. url = parsedTexture.url;
  27227. }
  27228. texture = new Texture(url, scene, !generateMipMaps);
  27229. }
  27230. return texture;
  27231. }
  27232. }, parsedTexture, scene);
  27233. // Update Sampling Mode
  27234. if (parsedTexture.samplingMode) {
  27235. var sampling = parsedTexture.samplingMode;
  27236. if (texture._samplingMode !== sampling) {
  27237. texture.updateSamplingMode(sampling);
  27238. }
  27239. }
  27240. // Animations
  27241. if (parsedTexture.animations) {
  27242. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27243. var parsedAnimation = parsedTexture.animations[animationIndex];
  27244. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27245. }
  27246. }
  27247. return texture;
  27248. };
  27249. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27250. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27251. if (noMipmap === void 0) { noMipmap = false; }
  27252. if (invertY === void 0) { invertY = true; }
  27253. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27254. if (onLoad === void 0) { onLoad = null; }
  27255. if (onError === void 0) { onError = null; }
  27256. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27257. if (name.substr(0, 5) !== "data:") {
  27258. name = "data:" + name;
  27259. }
  27260. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27261. };
  27262. // Constants
  27263. Texture.NEAREST_SAMPLINGMODE = 1;
  27264. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27265. Texture.BILINEAR_SAMPLINGMODE = 2;
  27266. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27267. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27268. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27269. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27270. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27271. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27272. Texture.NEAREST_LINEAR = 7;
  27273. Texture.NEAREST_NEAREST = 8;
  27274. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27275. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27276. Texture.LINEAR_LINEAR = 11;
  27277. Texture.LINEAR_NEAREST = 12;
  27278. Texture.EXPLICIT_MODE = 0;
  27279. Texture.SPHERICAL_MODE = 1;
  27280. Texture.PLANAR_MODE = 2;
  27281. Texture.CUBIC_MODE = 3;
  27282. Texture.PROJECTION_MODE = 4;
  27283. Texture.SKYBOX_MODE = 5;
  27284. Texture.INVCUBIC_MODE = 6;
  27285. Texture.EQUIRECTANGULAR_MODE = 7;
  27286. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27287. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27288. Texture.CLAMP_ADDRESSMODE = 0;
  27289. Texture.WRAP_ADDRESSMODE = 1;
  27290. Texture.MIRROR_ADDRESSMODE = 2;
  27291. /**
  27292. * 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
  27293. */
  27294. Texture.UseSerializedUrlIfAny = false;
  27295. __decorate([
  27296. BABYLON.serialize()
  27297. ], Texture.prototype, "url", void 0);
  27298. __decorate([
  27299. BABYLON.serialize()
  27300. ], Texture.prototype, "uOffset", void 0);
  27301. __decorate([
  27302. BABYLON.serialize()
  27303. ], Texture.prototype, "vOffset", void 0);
  27304. __decorate([
  27305. BABYLON.serialize()
  27306. ], Texture.prototype, "uScale", void 0);
  27307. __decorate([
  27308. BABYLON.serialize()
  27309. ], Texture.prototype, "vScale", void 0);
  27310. __decorate([
  27311. BABYLON.serialize()
  27312. ], Texture.prototype, "uAng", void 0);
  27313. __decorate([
  27314. BABYLON.serialize()
  27315. ], Texture.prototype, "vAng", void 0);
  27316. __decorate([
  27317. BABYLON.serialize()
  27318. ], Texture.prototype, "wAng", void 0);
  27319. __decorate([
  27320. BABYLON.serialize()
  27321. ], Texture.prototype, "isBlocking", null);
  27322. return Texture;
  27323. }(BABYLON.BaseTexture));
  27324. BABYLON.Texture = Texture;
  27325. })(BABYLON || (BABYLON = {}));
  27326. //# sourceMappingURL=babylon.texture.js.map
  27327. var BABYLON;
  27328. (function (BABYLON) {
  27329. var _InstancesBatch = /** @class */ (function () {
  27330. function _InstancesBatch() {
  27331. this.mustReturn = false;
  27332. this.visibleInstances = new Array();
  27333. this.renderSelf = new Array();
  27334. }
  27335. return _InstancesBatch;
  27336. }());
  27337. BABYLON._InstancesBatch = _InstancesBatch;
  27338. var Mesh = /** @class */ (function (_super) {
  27339. __extends(Mesh, _super);
  27340. /**
  27341. * @constructor
  27342. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27343. * @param {Scene} scene The scene to add this mesh to.
  27344. * @param {Node} parent The parent of this mesh, if it has one
  27345. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27346. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27347. * When false, achieved by calling a clone(), also passing False.
  27348. * This will make creation of children, recursive.
  27349. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27350. */
  27351. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27352. if (scene === void 0) { scene = null; }
  27353. if (parent === void 0) { parent = null; }
  27354. if (source === void 0) { source = null; }
  27355. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27356. var _this = _super.call(this, name, scene) || this;
  27357. // Events
  27358. /**
  27359. * An event triggered before rendering the mesh
  27360. * @type {BABYLON.Observable}
  27361. */
  27362. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27363. /**
  27364. * An event triggered after rendering the mesh
  27365. * @type {BABYLON.Observable}
  27366. */
  27367. _this.onAfterRenderObservable = new BABYLON.Observable();
  27368. /**
  27369. * An event triggered before drawing the mesh
  27370. * @type {BABYLON.Observable}
  27371. */
  27372. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27373. // Members
  27374. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27375. _this.instances = new Array();
  27376. _this._LODLevels = new Array();
  27377. _this._visibleInstances = {};
  27378. _this._renderIdForInstances = new Array();
  27379. _this._batchCache = new _InstancesBatch();
  27380. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27381. // Use by builder only to know what orientation were the mesh build in.
  27382. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27383. _this.overrideMaterialSideOrientation = null;
  27384. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27385. // Will be used to save a source mesh reference, If any
  27386. _this._source = null;
  27387. scene = _this.getScene();
  27388. if (source) {
  27389. // Source mesh
  27390. _this._source = source;
  27391. // Geometry
  27392. if (source._geometry) {
  27393. source._geometry.applyToMesh(_this);
  27394. }
  27395. // Deep copy
  27396. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27397. // Metadata
  27398. if (source.metadata && source.metadata.clone) {
  27399. _this.metadata = source.metadata.clone();
  27400. }
  27401. else {
  27402. _this.metadata = source.metadata;
  27403. }
  27404. // Tags
  27405. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27406. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27407. }
  27408. // Parent
  27409. _this.parent = source.parent;
  27410. // Pivot
  27411. _this.setPivotMatrix(source.getPivotMatrix());
  27412. _this.id = name + "." + source.id;
  27413. // Material
  27414. _this.material = source.material;
  27415. var index;
  27416. if (!doNotCloneChildren) {
  27417. // Children
  27418. var directDescendants = source.getDescendants(true);
  27419. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27420. var child = directDescendants[index_1];
  27421. if (child.clone) {
  27422. child.clone(name + "." + child.name, _this);
  27423. }
  27424. }
  27425. }
  27426. // Physics clone
  27427. var physicsEngine = _this.getScene().getPhysicsEngine();
  27428. if (clonePhysicsImpostor && physicsEngine) {
  27429. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27430. if (impostor) {
  27431. _this.physicsImpostor = impostor.clone(_this);
  27432. }
  27433. }
  27434. // Particles
  27435. for (index = 0; index < scene.particleSystems.length; index++) {
  27436. var system = scene.particleSystems[index];
  27437. if (system.emitter === source) {
  27438. system.clone(system.name, _this);
  27439. }
  27440. }
  27441. _this.computeWorldMatrix(true);
  27442. }
  27443. // Parent
  27444. if (parent !== null) {
  27445. _this.parent = parent;
  27446. }
  27447. return _this;
  27448. }
  27449. Object.defineProperty(Mesh, "FRONTSIDE", {
  27450. /**
  27451. * Mesh side orientation : usually the external or front surface
  27452. */
  27453. get: function () {
  27454. return Mesh._FRONTSIDE;
  27455. },
  27456. enumerable: true,
  27457. configurable: true
  27458. });
  27459. Object.defineProperty(Mesh, "BACKSIDE", {
  27460. /**
  27461. * Mesh side orientation : usually the internal or back surface
  27462. */
  27463. get: function () {
  27464. return Mesh._BACKSIDE;
  27465. },
  27466. enumerable: true,
  27467. configurable: true
  27468. });
  27469. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27470. /**
  27471. * Mesh side orientation : both internal and external or front and back surfaces
  27472. */
  27473. get: function () {
  27474. return Mesh._DOUBLESIDE;
  27475. },
  27476. enumerable: true,
  27477. configurable: true
  27478. });
  27479. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27480. /**
  27481. * Mesh side orientation : by default, `FRONTSIDE`
  27482. */
  27483. get: function () {
  27484. return Mesh._DEFAULTSIDE;
  27485. },
  27486. enumerable: true,
  27487. configurable: true
  27488. });
  27489. Object.defineProperty(Mesh, "NO_CAP", {
  27490. /**
  27491. * Mesh cap setting : no cap
  27492. */
  27493. get: function () {
  27494. return Mesh._NO_CAP;
  27495. },
  27496. enumerable: true,
  27497. configurable: true
  27498. });
  27499. Object.defineProperty(Mesh, "CAP_START", {
  27500. /**
  27501. * Mesh cap setting : one cap at the beginning of the mesh
  27502. */
  27503. get: function () {
  27504. return Mesh._CAP_START;
  27505. },
  27506. enumerable: true,
  27507. configurable: true
  27508. });
  27509. Object.defineProperty(Mesh, "CAP_END", {
  27510. /**
  27511. * Mesh cap setting : one cap at the end of the mesh
  27512. */
  27513. get: function () {
  27514. return Mesh._CAP_END;
  27515. },
  27516. enumerable: true,
  27517. configurable: true
  27518. });
  27519. Object.defineProperty(Mesh, "CAP_ALL", {
  27520. /**
  27521. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27522. */
  27523. get: function () {
  27524. return Mesh._CAP_ALL;
  27525. },
  27526. enumerable: true,
  27527. configurable: true
  27528. });
  27529. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27530. set: function (callback) {
  27531. if (this._onBeforeDrawObserver) {
  27532. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27533. }
  27534. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27535. },
  27536. enumerable: true,
  27537. configurable: true
  27538. });
  27539. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27540. get: function () {
  27541. return this._morphTargetManager;
  27542. },
  27543. set: function (value) {
  27544. if (this._morphTargetManager === value) {
  27545. return;
  27546. }
  27547. this._morphTargetManager = value;
  27548. this._syncGeometryWithMorphTargetManager();
  27549. },
  27550. enumerable: true,
  27551. configurable: true
  27552. });
  27553. Object.defineProperty(Mesh.prototype, "source", {
  27554. get: function () {
  27555. return this._source;
  27556. },
  27557. enumerable: true,
  27558. configurable: true
  27559. });
  27560. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27561. get: function () {
  27562. return this._unIndexed;
  27563. },
  27564. set: function (value) {
  27565. if (this._unIndexed !== value) {
  27566. this._unIndexed = value;
  27567. this._markSubMeshesAsAttributesDirty();
  27568. }
  27569. },
  27570. enumerable: true,
  27571. configurable: true
  27572. });
  27573. // Methods
  27574. /**
  27575. * Returns the string "Mesh".
  27576. */
  27577. Mesh.prototype.getClassName = function () {
  27578. return "Mesh";
  27579. };
  27580. /**
  27581. * Returns a string.
  27582. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27583. */
  27584. Mesh.prototype.toString = function (fullDetails) {
  27585. var ret = _super.prototype.toString.call(this, fullDetails);
  27586. ret += ", n vertices: " + this.getTotalVertices();
  27587. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27588. if (this.animations) {
  27589. for (var i = 0; i < this.animations.length; i++) {
  27590. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27591. }
  27592. }
  27593. if (fullDetails) {
  27594. if (this._geometry) {
  27595. var ib = this.getIndices();
  27596. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27597. if (vb && ib) {
  27598. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27599. }
  27600. }
  27601. else {
  27602. ret += ", flat shading: UNKNOWN";
  27603. }
  27604. }
  27605. return ret;
  27606. };
  27607. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27608. /**
  27609. * True if the mesh has some Levels Of Details (LOD).
  27610. * Returns a boolean.
  27611. */
  27612. get: function () {
  27613. return this._LODLevels.length > 0;
  27614. },
  27615. enumerable: true,
  27616. configurable: true
  27617. });
  27618. /**
  27619. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27620. * @returns an array of {BABYLON.MeshLODLevel}
  27621. */
  27622. Mesh.prototype.getLODLevels = function () {
  27623. return this._LODLevels;
  27624. };
  27625. Mesh.prototype._sortLODLevels = function () {
  27626. this._LODLevels.sort(function (a, b) {
  27627. if (a.distance < b.distance) {
  27628. return 1;
  27629. }
  27630. if (a.distance > b.distance) {
  27631. return -1;
  27632. }
  27633. return 0;
  27634. });
  27635. };
  27636. /**
  27637. * Add a mesh as LOD level triggered at the given distance.
  27638. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27639. * @param {number} distance The distance from the center of the object to show this level
  27640. * @param {Mesh} mesh The mesh to be added as LOD level
  27641. * @return {Mesh} This mesh (for chaining)
  27642. */
  27643. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27644. if (mesh && mesh._masterMesh) {
  27645. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27646. return this;
  27647. }
  27648. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27649. this._LODLevels.push(level);
  27650. if (mesh) {
  27651. mesh._masterMesh = this;
  27652. }
  27653. this._sortLODLevels();
  27654. return this;
  27655. };
  27656. /**
  27657. * Returns the LOD level mesh at the passed distance or null if not found.
  27658. * It is related to the method `addLODLevel(distance, mesh)`.
  27659. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27660. * Returns an object Mesh or `null`.
  27661. */
  27662. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27663. for (var index = 0; index < this._LODLevels.length; index++) {
  27664. var level = this._LODLevels[index];
  27665. if (level.distance === distance) {
  27666. return level.mesh;
  27667. }
  27668. }
  27669. return null;
  27670. };
  27671. /**
  27672. * Remove a mesh from the LOD array
  27673. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27674. * @param {Mesh} mesh The mesh to be removed.
  27675. * @return {Mesh} This mesh (for chaining)
  27676. */
  27677. Mesh.prototype.removeLODLevel = function (mesh) {
  27678. for (var index = 0; index < this._LODLevels.length; index++) {
  27679. if (this._LODLevels[index].mesh === mesh) {
  27680. this._LODLevels.splice(index, 1);
  27681. if (mesh) {
  27682. mesh._masterMesh = null;
  27683. }
  27684. }
  27685. }
  27686. this._sortLODLevels();
  27687. return this;
  27688. };
  27689. /**
  27690. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27691. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27692. */
  27693. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27694. if (!this._LODLevels || this._LODLevels.length === 0) {
  27695. return this;
  27696. }
  27697. var bSphere;
  27698. if (boundingSphere) {
  27699. bSphere = boundingSphere;
  27700. }
  27701. else {
  27702. var boundingInfo = this.getBoundingInfo();
  27703. bSphere = boundingInfo.boundingSphere;
  27704. }
  27705. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27706. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27707. if (this.onLODLevelSelection) {
  27708. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27709. }
  27710. return this;
  27711. }
  27712. for (var index = 0; index < this._LODLevels.length; index++) {
  27713. var level = this._LODLevels[index];
  27714. if (level.distance < distanceToCamera) {
  27715. if (level.mesh) {
  27716. level.mesh._preActivate();
  27717. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27718. }
  27719. if (this.onLODLevelSelection) {
  27720. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27721. }
  27722. return level.mesh;
  27723. }
  27724. }
  27725. if (this.onLODLevelSelection) {
  27726. this.onLODLevelSelection(distanceToCamera, this, this);
  27727. }
  27728. return this;
  27729. };
  27730. Object.defineProperty(Mesh.prototype, "geometry", {
  27731. /**
  27732. * Returns the mesh internal Geometry object.
  27733. */
  27734. get: function () {
  27735. return this._geometry;
  27736. },
  27737. enumerable: true,
  27738. configurable: true
  27739. });
  27740. /**
  27741. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27742. */
  27743. Mesh.prototype.getTotalVertices = function () {
  27744. if (this._geometry === null || this._geometry === undefined) {
  27745. return 0;
  27746. }
  27747. return this._geometry.getTotalVertices();
  27748. };
  27749. /**
  27750. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27751. * 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.
  27752. * You can force the copy with forceCopy === true
  27753. * Returns null if the mesh has no geometry or no vertex buffer.
  27754. * Possible `kind` values :
  27755. * - BABYLON.VertexBuffer.PositionKind
  27756. * - BABYLON.VertexBuffer.UVKind
  27757. * - BABYLON.VertexBuffer.UV2Kind
  27758. * - BABYLON.VertexBuffer.UV3Kind
  27759. * - BABYLON.VertexBuffer.UV4Kind
  27760. * - BABYLON.VertexBuffer.UV5Kind
  27761. * - BABYLON.VertexBuffer.UV6Kind
  27762. * - BABYLON.VertexBuffer.ColorKind
  27763. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27764. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27765. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27766. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27767. */
  27768. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27769. if (!this._geometry) {
  27770. return null;
  27771. }
  27772. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27773. };
  27774. /**
  27775. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27776. * Returns `null` if the mesh has no geometry.
  27777. * Possible `kind` values :
  27778. * - BABYLON.VertexBuffer.PositionKind
  27779. * - BABYLON.VertexBuffer.UVKind
  27780. * - BABYLON.VertexBuffer.UV2Kind
  27781. * - BABYLON.VertexBuffer.UV3Kind
  27782. * - BABYLON.VertexBuffer.UV4Kind
  27783. * - BABYLON.VertexBuffer.UV5Kind
  27784. * - BABYLON.VertexBuffer.UV6Kind
  27785. * - BABYLON.VertexBuffer.ColorKind
  27786. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27787. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27788. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27789. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27790. */
  27791. Mesh.prototype.getVertexBuffer = function (kind) {
  27792. if (!this._geometry) {
  27793. return null;
  27794. }
  27795. return this._geometry.getVertexBuffer(kind);
  27796. };
  27797. /**
  27798. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27799. * Possible `kind` values :
  27800. * - BABYLON.VertexBuffer.PositionKind
  27801. * - BABYLON.VertexBuffer.UVKind
  27802. * - BABYLON.VertexBuffer.UV2Kind
  27803. * - BABYLON.VertexBuffer.UV3Kind
  27804. * - BABYLON.VertexBuffer.UV4Kind
  27805. * - BABYLON.VertexBuffer.UV5Kind
  27806. * - BABYLON.VertexBuffer.UV6Kind
  27807. * - BABYLON.VertexBuffer.ColorKind
  27808. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27809. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27810. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27811. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27812. */
  27813. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27814. if (!this._geometry) {
  27815. if (this._delayInfo) {
  27816. return this._delayInfo.indexOf(kind) !== -1;
  27817. }
  27818. return false;
  27819. }
  27820. return this._geometry.isVerticesDataPresent(kind);
  27821. };
  27822. /**
  27823. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27824. * Possible `kind` values :
  27825. * - BABYLON.VertexBuffer.PositionKind
  27826. * - BABYLON.VertexBuffer.UVKind
  27827. * - BABYLON.VertexBuffer.UV2Kind
  27828. * - BABYLON.VertexBuffer.UV3Kind
  27829. * - BABYLON.VertexBuffer.UV4Kind
  27830. * - BABYLON.VertexBuffer.UV5Kind
  27831. * - BABYLON.VertexBuffer.UV6Kind
  27832. * - BABYLON.VertexBuffer.ColorKind
  27833. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27834. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27835. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27836. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27837. */
  27838. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27839. if (!this._geometry) {
  27840. if (this._delayInfo) {
  27841. return this._delayInfo.indexOf(kind) !== -1;
  27842. }
  27843. return false;
  27844. }
  27845. return this._geometry.isVertexBufferUpdatable(kind);
  27846. };
  27847. /**
  27848. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27849. * Possible `kind` values :
  27850. * - BABYLON.VertexBuffer.PositionKind
  27851. * - BABYLON.VertexBuffer.UVKind
  27852. * - BABYLON.VertexBuffer.UV2Kind
  27853. * - BABYLON.VertexBuffer.UV3Kind
  27854. * - BABYLON.VertexBuffer.UV4Kind
  27855. * - BABYLON.VertexBuffer.UV5Kind
  27856. * - BABYLON.VertexBuffer.UV6Kind
  27857. * - BABYLON.VertexBuffer.ColorKind
  27858. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27859. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27860. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27861. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27862. */
  27863. Mesh.prototype.getVerticesDataKinds = function () {
  27864. if (!this._geometry) {
  27865. var result = new Array();
  27866. if (this._delayInfo) {
  27867. this._delayInfo.forEach(function (kind, index, array) {
  27868. result.push(kind);
  27869. });
  27870. }
  27871. return result;
  27872. }
  27873. return this._geometry.getVerticesDataKinds();
  27874. };
  27875. /**
  27876. * Returns a positive integer : the total number of indices in this mesh geometry.
  27877. * Returns zero if the mesh has no geometry.
  27878. */
  27879. Mesh.prototype.getTotalIndices = function () {
  27880. if (!this._geometry) {
  27881. return 0;
  27882. }
  27883. return this._geometry.getTotalIndices();
  27884. };
  27885. /**
  27886. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27887. * 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.
  27888. * Returns an empty array if the mesh has no geometry.
  27889. */
  27890. Mesh.prototype.getIndices = function (copyWhenShared) {
  27891. if (!this._geometry) {
  27892. return [];
  27893. }
  27894. return this._geometry.getIndices(copyWhenShared);
  27895. };
  27896. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27897. get: function () {
  27898. return this._masterMesh !== null && this._masterMesh !== undefined;
  27899. },
  27900. enumerable: true,
  27901. configurable: true
  27902. });
  27903. /**
  27904. * Determine if the current mesh is ready to be rendered
  27905. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27906. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27907. * @returns true if all associated assets are ready (material, textures, shaders)
  27908. */
  27909. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27910. if (completeCheck === void 0) { completeCheck = false; }
  27911. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27912. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27913. return false;
  27914. }
  27915. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27916. return false;
  27917. }
  27918. if (!this.subMeshes || this.subMeshes.length === 0) {
  27919. return true;
  27920. }
  27921. if (!completeCheck) {
  27922. return true;
  27923. }
  27924. var engine = this.getEngine();
  27925. var scene = this.getScene();
  27926. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27927. this.computeWorldMatrix();
  27928. var mat = this.material || scene.defaultMaterial;
  27929. if (mat) {
  27930. if (mat.storeEffectOnSubMeshes) {
  27931. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27932. var subMesh = _a[_i];
  27933. var effectiveMaterial = subMesh.getMaterial();
  27934. if (effectiveMaterial) {
  27935. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27936. return false;
  27937. }
  27938. }
  27939. }
  27940. }
  27941. else {
  27942. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27943. return false;
  27944. }
  27945. }
  27946. }
  27947. // Shadows
  27948. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27949. var light = _c[_b];
  27950. var generator = light.getShadowGenerator();
  27951. if (generator) {
  27952. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27953. var subMesh = _e[_d];
  27954. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27955. return false;
  27956. }
  27957. }
  27958. }
  27959. }
  27960. // LOD
  27961. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27962. var lod = _g[_f];
  27963. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27964. return false;
  27965. }
  27966. }
  27967. return true;
  27968. };
  27969. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27970. /**
  27971. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27972. * This property is pertinent only for updatable parametric shapes.
  27973. */
  27974. get: function () {
  27975. return this._areNormalsFrozen;
  27976. },
  27977. enumerable: true,
  27978. configurable: true
  27979. });
  27980. /**
  27981. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27982. * It has no effect at all on other shapes.
  27983. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27984. * Returns the Mesh.
  27985. */
  27986. Mesh.prototype.freezeNormals = function () {
  27987. this._areNormalsFrozen = true;
  27988. return this;
  27989. };
  27990. /**
  27991. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27992. * It has no effect at all on other shapes.
  27993. * It reactivates the mesh normals computation if it was previously frozen.
  27994. * Returns the Mesh.
  27995. */
  27996. Mesh.prototype.unfreezeNormals = function () {
  27997. this._areNormalsFrozen = false;
  27998. return this;
  27999. };
  28000. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28001. /**
  28002. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28003. */
  28004. set: function (count) {
  28005. this._overridenInstanceCount = count;
  28006. },
  28007. enumerable: true,
  28008. configurable: true
  28009. });
  28010. // Methods
  28011. Mesh.prototype._preActivate = function () {
  28012. var sceneRenderId = this.getScene().getRenderId();
  28013. if (this._preActivateId === sceneRenderId) {
  28014. return this;
  28015. }
  28016. this._preActivateId = sceneRenderId;
  28017. this._visibleInstances = null;
  28018. return this;
  28019. };
  28020. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28021. if (this._visibleInstances) {
  28022. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28023. }
  28024. return this;
  28025. };
  28026. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28027. if (!this._visibleInstances) {
  28028. this._visibleInstances = {};
  28029. this._visibleInstances.defaultRenderId = renderId;
  28030. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28031. }
  28032. if (!this._visibleInstances[renderId]) {
  28033. this._visibleInstances[renderId] = new Array();
  28034. }
  28035. this._visibleInstances[renderId].push(instance);
  28036. return this;
  28037. };
  28038. /**
  28039. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28040. * This means the mesh underlying bounding box and sphere are recomputed.
  28041. * Returns the Mesh.
  28042. */
  28043. Mesh.prototype.refreshBoundingInfo = function () {
  28044. return this._refreshBoundingInfo(false);
  28045. };
  28046. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28047. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28048. return this;
  28049. }
  28050. var data = this._getPositionData(applySkeleton);
  28051. if (data) {
  28052. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28053. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28054. }
  28055. if (this.subMeshes) {
  28056. for (var index = 0; index < this.subMeshes.length; index++) {
  28057. this.subMeshes[index].refreshBoundingInfo();
  28058. }
  28059. }
  28060. this._updateBoundingInfo();
  28061. return this;
  28062. };
  28063. Mesh.prototype._getPositionData = function (applySkeleton) {
  28064. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28065. if (data && applySkeleton && this.skeleton) {
  28066. data = BABYLON.Tools.Slice(data);
  28067. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28068. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28069. if (matricesWeightsData && matricesIndicesData) {
  28070. var needExtras = this.numBoneInfluencers > 4;
  28071. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28072. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28073. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28074. var tempVector = BABYLON.Tmp.Vector3[0];
  28075. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28076. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28077. var matWeightIdx = 0;
  28078. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28079. finalMatrix.reset();
  28080. var inf;
  28081. var weight;
  28082. for (inf = 0; inf < 4; inf++) {
  28083. weight = matricesWeightsData[matWeightIdx + inf];
  28084. if (weight <= 0)
  28085. break;
  28086. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28087. finalMatrix.addToSelf(tempMatrix);
  28088. }
  28089. if (needExtras) {
  28090. for (inf = 0; inf < 4; inf++) {
  28091. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28092. if (weight <= 0)
  28093. break;
  28094. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28095. finalMatrix.addToSelf(tempMatrix);
  28096. }
  28097. }
  28098. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28099. tempVector.toArray(data, index);
  28100. }
  28101. }
  28102. }
  28103. return data;
  28104. };
  28105. Mesh.prototype._createGlobalSubMesh = function (force) {
  28106. var totalVertices = this.getTotalVertices();
  28107. if (!totalVertices || !this.getIndices()) {
  28108. return null;
  28109. }
  28110. // Check if we need to recreate the submeshes
  28111. if (this.subMeshes && this.subMeshes.length > 0) {
  28112. var ib = this.getIndices();
  28113. if (!ib) {
  28114. return null;
  28115. }
  28116. var totalIndices = ib.length;
  28117. var needToRecreate = false;
  28118. if (force) {
  28119. needToRecreate = true;
  28120. }
  28121. else {
  28122. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28123. var submesh = _a[_i];
  28124. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28125. needToRecreate = true;
  28126. break;
  28127. }
  28128. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28129. needToRecreate = true;
  28130. break;
  28131. }
  28132. }
  28133. }
  28134. if (!needToRecreate) {
  28135. return this.subMeshes[0];
  28136. }
  28137. }
  28138. this.releaseSubMeshes();
  28139. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28140. };
  28141. Mesh.prototype.subdivide = function (count) {
  28142. if (count < 1) {
  28143. return;
  28144. }
  28145. var totalIndices = this.getTotalIndices();
  28146. var subdivisionSize = (totalIndices / count) | 0;
  28147. var offset = 0;
  28148. // Ensure that subdivisionSize is a multiple of 3
  28149. while (subdivisionSize % 3 !== 0) {
  28150. subdivisionSize++;
  28151. }
  28152. this.releaseSubMeshes();
  28153. for (var index = 0; index < count; index++) {
  28154. if (offset >= totalIndices) {
  28155. break;
  28156. }
  28157. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28158. offset += subdivisionSize;
  28159. }
  28160. this.synchronizeInstances();
  28161. };
  28162. /**
  28163. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28164. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28165. * The `data` are either a numeric array either a Float32Array.
  28166. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28167. * 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).
  28168. * Note that a new underlying VertexBuffer object is created each call.
  28169. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28170. *
  28171. * Possible `kind` values :
  28172. * - BABYLON.VertexBuffer.PositionKind
  28173. * - BABYLON.VertexBuffer.UVKind
  28174. * - BABYLON.VertexBuffer.UV2Kind
  28175. * - BABYLON.VertexBuffer.UV3Kind
  28176. * - BABYLON.VertexBuffer.UV4Kind
  28177. * - BABYLON.VertexBuffer.UV5Kind
  28178. * - BABYLON.VertexBuffer.UV6Kind
  28179. * - BABYLON.VertexBuffer.ColorKind
  28180. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28181. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28182. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28183. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28184. *
  28185. * Returns the Mesh.
  28186. */
  28187. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28188. if (updatable === void 0) { updatable = false; }
  28189. if (!this._geometry) {
  28190. var vertexData = new BABYLON.VertexData();
  28191. vertexData.set(data, kind);
  28192. var scene = this.getScene();
  28193. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28194. }
  28195. else {
  28196. this._geometry.setVerticesData(kind, data, updatable, stride);
  28197. }
  28198. return this;
  28199. };
  28200. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28201. if (updatable === void 0) { updatable = true; }
  28202. var vb = this.getVertexBuffer(kind);
  28203. if (!vb || vb.isUpdatable() === updatable) {
  28204. return;
  28205. }
  28206. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28207. };
  28208. /**
  28209. * Sets the mesh VertexBuffer.
  28210. * Returns the Mesh.
  28211. */
  28212. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28213. if (!this._geometry) {
  28214. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28215. }
  28216. this._geometry.setVerticesBuffer(buffer);
  28217. return this;
  28218. };
  28219. /**
  28220. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28221. * If the mesh has no geometry, it is simply returned as it is.
  28222. * The `data` are either a numeric array either a Float32Array.
  28223. * No new underlying VertexBuffer object is created.
  28224. * 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.
  28225. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28226. *
  28227. * Possible `kind` values :
  28228. * - BABYLON.VertexBuffer.PositionKind
  28229. * - BABYLON.VertexBuffer.UVKind
  28230. * - BABYLON.VertexBuffer.UV2Kind
  28231. * - BABYLON.VertexBuffer.UV3Kind
  28232. * - BABYLON.VertexBuffer.UV4Kind
  28233. * - BABYLON.VertexBuffer.UV5Kind
  28234. * - BABYLON.VertexBuffer.UV6Kind
  28235. * - BABYLON.VertexBuffer.ColorKind
  28236. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28237. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28238. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28239. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28240. *
  28241. * Returns the Mesh.
  28242. */
  28243. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28244. if (!this._geometry) {
  28245. return this;
  28246. }
  28247. if (!makeItUnique) {
  28248. this._geometry.updateVerticesData(kind, data, updateExtends);
  28249. }
  28250. else {
  28251. this.makeGeometryUnique();
  28252. this.updateVerticesData(kind, data, updateExtends, false);
  28253. }
  28254. return this;
  28255. };
  28256. /**
  28257. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28258. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28259. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28260. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28261. * Returns the Mesh.
  28262. */
  28263. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28264. if (computeNormals === void 0) { computeNormals = true; }
  28265. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28266. if (!positions) {
  28267. return this;
  28268. }
  28269. positionFunction(positions);
  28270. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28271. if (computeNormals) {
  28272. var indices = this.getIndices();
  28273. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28274. if (!normals) {
  28275. return this;
  28276. }
  28277. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28278. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28279. }
  28280. return this;
  28281. };
  28282. /**
  28283. * Creates a un-shared specific occurence of the geometry for the mesh.
  28284. * Returns the Mesh.
  28285. */
  28286. Mesh.prototype.makeGeometryUnique = function () {
  28287. if (!this._geometry) {
  28288. return this;
  28289. }
  28290. var oldGeometry = this._geometry;
  28291. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28292. oldGeometry.releaseForMesh(this, true);
  28293. geometry.applyToMesh(this);
  28294. return this;
  28295. };
  28296. /**
  28297. * Sets the mesh indices.
  28298. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28299. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28300. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28301. * This method creates a new index buffer each call.
  28302. * Returns the Mesh.
  28303. */
  28304. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28305. if (totalVertices === void 0) { totalVertices = null; }
  28306. if (updatable === void 0) { updatable = false; }
  28307. if (!this._geometry) {
  28308. var vertexData = new BABYLON.VertexData();
  28309. vertexData.indices = indices;
  28310. var scene = this.getScene();
  28311. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28312. }
  28313. else {
  28314. this._geometry.setIndices(indices, totalVertices, updatable);
  28315. }
  28316. return this;
  28317. };
  28318. /**
  28319. * Update the current index buffer
  28320. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28321. * Returns the Mesh.
  28322. */
  28323. Mesh.prototype.updateIndices = function (indices, offset) {
  28324. if (!this._geometry) {
  28325. return this;
  28326. }
  28327. this._geometry.updateIndices(indices, offset);
  28328. return this;
  28329. };
  28330. /**
  28331. * Invert the geometry to move from a right handed system to a left handed one.
  28332. * Returns the Mesh.
  28333. */
  28334. Mesh.prototype.toLeftHanded = function () {
  28335. if (!this._geometry) {
  28336. return this;
  28337. }
  28338. this._geometry.toLeftHanded();
  28339. return this;
  28340. };
  28341. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28342. if (!this._geometry) {
  28343. return this;
  28344. }
  28345. var engine = this.getScene().getEngine();
  28346. // Wireframe
  28347. var indexToBind;
  28348. if (this._unIndexed) {
  28349. indexToBind = null;
  28350. }
  28351. else {
  28352. switch (fillMode) {
  28353. case BABYLON.Material.PointFillMode:
  28354. indexToBind = null;
  28355. break;
  28356. case BABYLON.Material.WireFrameFillMode:
  28357. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28358. break;
  28359. default:
  28360. case BABYLON.Material.TriangleFillMode:
  28361. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28362. break;
  28363. }
  28364. }
  28365. // VBOs
  28366. this._geometry._bind(effect, indexToBind);
  28367. return this;
  28368. };
  28369. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28370. if (alternate === void 0) { alternate = false; }
  28371. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28372. return this;
  28373. }
  28374. this.onBeforeDrawObservable.notifyObservers(this);
  28375. var scene = this.getScene();
  28376. var engine = scene.getEngine();
  28377. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28378. // or triangles as points
  28379. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28380. }
  28381. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28382. // Triangles as wireframe
  28383. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28384. }
  28385. else {
  28386. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28387. }
  28388. if (scene._isAlternateRenderingEnabled && !alternate) {
  28389. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28390. if (!effect || !scene.activeCamera) {
  28391. return this;
  28392. }
  28393. scene._switchToAlternateCameraConfiguration(true);
  28394. this._effectiveMaterial.bindView(effect);
  28395. this._effectiveMaterial.bindViewProjection(effect);
  28396. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28397. this._draw(subMesh, fillMode, instancesCount, true);
  28398. engine.setViewport(scene.activeCamera.viewport);
  28399. scene._switchToAlternateCameraConfiguration(false);
  28400. this._effectiveMaterial.bindView(effect);
  28401. this._effectiveMaterial.bindViewProjection(effect);
  28402. }
  28403. return this;
  28404. };
  28405. /**
  28406. * Registers for this mesh a javascript function called just before the rendering process.
  28407. * This function is passed the current mesh.
  28408. * Return the Mesh.
  28409. */
  28410. Mesh.prototype.registerBeforeRender = function (func) {
  28411. this.onBeforeRenderObservable.add(func);
  28412. return this;
  28413. };
  28414. /**
  28415. * Disposes a previously registered javascript function called before the rendering.
  28416. * This function is passed the current mesh.
  28417. * Returns the Mesh.
  28418. */
  28419. Mesh.prototype.unregisterBeforeRender = function (func) {
  28420. this.onBeforeRenderObservable.removeCallback(func);
  28421. return this;
  28422. };
  28423. /**
  28424. * Registers for this mesh a javascript function called just after the rendering is complete.
  28425. * This function is passed the current mesh.
  28426. * Returns the Mesh.
  28427. */
  28428. Mesh.prototype.registerAfterRender = function (func) {
  28429. this.onAfterRenderObservable.add(func);
  28430. return this;
  28431. };
  28432. /**
  28433. * Disposes a previously registered javascript function called after the rendering.
  28434. * This function is passed the current mesh.
  28435. * Return the Mesh.
  28436. */
  28437. Mesh.prototype.unregisterAfterRender = function (func) {
  28438. this.onAfterRenderObservable.removeCallback(func);
  28439. return this;
  28440. };
  28441. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28442. var scene = this.getScene();
  28443. this._batchCache.mustReturn = false;
  28444. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28445. this._batchCache.visibleInstances[subMeshId] = null;
  28446. if (this._visibleInstances) {
  28447. var currentRenderId = scene.getRenderId();
  28448. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28449. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28450. var selfRenderId = this._renderId;
  28451. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28452. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28453. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28454. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28455. }
  28456. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28457. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28458. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28459. this._batchCache.mustReturn = true;
  28460. return this._batchCache;
  28461. }
  28462. if (currentRenderId !== selfRenderId) {
  28463. this._batchCache.renderSelf[subMeshId] = false;
  28464. }
  28465. }
  28466. this._renderIdForInstances[subMeshId] = currentRenderId;
  28467. }
  28468. return this._batchCache;
  28469. };
  28470. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28471. var visibleInstances = batch.visibleInstances[subMesh._id];
  28472. if (!visibleInstances) {
  28473. return this;
  28474. }
  28475. var matricesCount = visibleInstances.length + 1;
  28476. var bufferSize = matricesCount * 16 * 4;
  28477. var currentInstancesBufferSize = this._instancesBufferSize;
  28478. var instancesBuffer = this._instancesBuffer;
  28479. while (this._instancesBufferSize < bufferSize) {
  28480. this._instancesBufferSize *= 2;
  28481. }
  28482. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28483. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28484. }
  28485. var offset = 0;
  28486. var instancesCount = 0;
  28487. var world = this.getWorldMatrix();
  28488. if (batch.renderSelf[subMesh._id]) {
  28489. world.copyToArray(this._instancesData, offset);
  28490. offset += 16;
  28491. instancesCount++;
  28492. }
  28493. if (visibleInstances) {
  28494. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28495. var instance = visibleInstances[instanceIndex];
  28496. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28497. offset += 16;
  28498. instancesCount++;
  28499. }
  28500. }
  28501. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28502. if (instancesBuffer) {
  28503. instancesBuffer.dispose();
  28504. }
  28505. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28506. this._instancesBuffer = instancesBuffer;
  28507. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28508. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28509. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28510. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28511. }
  28512. else {
  28513. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28514. }
  28515. this._bind(subMesh, effect, fillMode);
  28516. this._draw(subMesh, fillMode, instancesCount);
  28517. engine.unbindInstanceAttributes();
  28518. return this;
  28519. };
  28520. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28521. var scene = this.getScene();
  28522. var engine = scene.getEngine();
  28523. if (hardwareInstancedRendering) {
  28524. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28525. }
  28526. else {
  28527. if (batch.renderSelf[subMesh._id]) {
  28528. // Draw
  28529. if (onBeforeDraw) {
  28530. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28531. }
  28532. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28533. }
  28534. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28535. if (visibleInstancesForSubMesh) {
  28536. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28537. var instance = visibleInstancesForSubMesh[instanceIndex];
  28538. // World
  28539. var world = instance.getWorldMatrix();
  28540. if (onBeforeDraw) {
  28541. onBeforeDraw(true, world, effectiveMaterial);
  28542. }
  28543. // Draw
  28544. this._draw(subMesh, fillMode);
  28545. }
  28546. }
  28547. }
  28548. return this;
  28549. };
  28550. /**
  28551. * Triggers the draw call for the mesh.
  28552. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28553. * Returns the Mesh.
  28554. */
  28555. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28556. this.checkOcclusionQuery();
  28557. if (this._isOccluded) {
  28558. return this;
  28559. }
  28560. var scene = this.getScene();
  28561. // Managing instances
  28562. var batch = this._getInstancesRenderList(subMesh._id);
  28563. if (batch.mustReturn) {
  28564. return this;
  28565. }
  28566. // Checking geometry state
  28567. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28568. return this;
  28569. }
  28570. this.onBeforeRenderObservable.notifyObservers(this);
  28571. var engine = scene.getEngine();
  28572. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28573. // Material
  28574. var material = subMesh.getMaterial();
  28575. if (!material) {
  28576. return this;
  28577. }
  28578. this._effectiveMaterial = material;
  28579. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28580. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28581. return this;
  28582. }
  28583. }
  28584. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28585. return this;
  28586. }
  28587. // Alpha mode
  28588. if (enableAlphaMode) {
  28589. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28590. }
  28591. // Outline - step 1
  28592. var savedDepthWrite = engine.getDepthWrite();
  28593. if (this.renderOutline) {
  28594. engine.setDepthWrite(false);
  28595. scene.getOutlineRenderer().render(subMesh, batch);
  28596. engine.setDepthWrite(savedDepthWrite);
  28597. }
  28598. var effect;
  28599. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28600. effect = subMesh.effect;
  28601. }
  28602. else {
  28603. effect = this._effectiveMaterial.getEffect();
  28604. }
  28605. if (!effect) {
  28606. return this;
  28607. }
  28608. var sideOrientation = this.overrideMaterialSideOrientation;
  28609. if (sideOrientation == null) {
  28610. sideOrientation = this._effectiveMaterial.sideOrientation;
  28611. if (this._getWorldMatrixDeterminant() < 0) {
  28612. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28613. }
  28614. }
  28615. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28616. if (this._effectiveMaterial.forceDepthWrite) {
  28617. engine.setDepthWrite(true);
  28618. }
  28619. // Bind
  28620. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28621. if (!hardwareInstancedRendering) {
  28622. this._bind(subMesh, effect, fillMode);
  28623. }
  28624. var world = this.getWorldMatrix();
  28625. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28626. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28627. }
  28628. else {
  28629. this._effectiveMaterial.bind(world, this);
  28630. }
  28631. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28632. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28633. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28634. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28635. }
  28636. // Draw
  28637. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28638. // Unbind
  28639. this._effectiveMaterial.unbind();
  28640. // Outline - step 2
  28641. if (this.renderOutline && savedDepthWrite) {
  28642. engine.setDepthWrite(true);
  28643. engine.setColorWrite(false);
  28644. scene.getOutlineRenderer().render(subMesh, batch);
  28645. engine.setColorWrite(true);
  28646. }
  28647. // Overlay
  28648. if (this.renderOverlay) {
  28649. var currentMode = engine.getAlphaMode();
  28650. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28651. scene.getOutlineRenderer().render(subMesh, batch, true);
  28652. engine.setAlphaMode(currentMode);
  28653. }
  28654. this.onAfterRenderObservable.notifyObservers(this);
  28655. return this;
  28656. };
  28657. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28658. if (isInstance && effectiveMaterial) {
  28659. effectiveMaterial.bindOnlyWorldMatrix(world);
  28660. }
  28661. };
  28662. /**
  28663. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28664. */
  28665. Mesh.prototype.getEmittedParticleSystems = function () {
  28666. var results = new Array();
  28667. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28668. var particleSystem = this.getScene().particleSystems[index];
  28669. if (particleSystem.emitter === this) {
  28670. results.push(particleSystem);
  28671. }
  28672. }
  28673. return results;
  28674. };
  28675. /**
  28676. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28677. */
  28678. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28679. var results = new Array();
  28680. var descendants = this.getDescendants();
  28681. descendants.push(this);
  28682. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28683. var particleSystem = this.getScene().particleSystems[index];
  28684. var emitter = particleSystem.emitter;
  28685. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28686. results.push(particleSystem);
  28687. }
  28688. }
  28689. return results;
  28690. };
  28691. Mesh.prototype._checkDelayState = function () {
  28692. var scene = this.getScene();
  28693. if (this._geometry) {
  28694. this._geometry.load(scene);
  28695. }
  28696. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28697. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28698. this._queueLoad(scene);
  28699. }
  28700. return this;
  28701. };
  28702. Mesh.prototype._queueLoad = function (scene) {
  28703. var _this = this;
  28704. scene._addPendingData(this);
  28705. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28706. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28707. if (data instanceof ArrayBuffer) {
  28708. _this._delayLoadingFunction(data, _this);
  28709. }
  28710. else {
  28711. _this._delayLoadingFunction(JSON.parse(data), _this);
  28712. }
  28713. _this.instances.forEach(function (instance) {
  28714. instance._syncSubMeshes();
  28715. });
  28716. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28717. scene._removePendingData(_this);
  28718. }, function () { }, scene.database, getBinaryData);
  28719. return this;
  28720. };
  28721. /**
  28722. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28723. */
  28724. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28725. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28726. return false;
  28727. }
  28728. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28729. return false;
  28730. }
  28731. this._checkDelayState();
  28732. return true;
  28733. };
  28734. /**
  28735. * Sets the mesh material by the material or multiMaterial `id` property.
  28736. * The material `id` is a string identifying the material or the multiMaterial.
  28737. * This method returns the Mesh.
  28738. */
  28739. Mesh.prototype.setMaterialByID = function (id) {
  28740. var materials = this.getScene().materials;
  28741. var index;
  28742. for (index = materials.length - 1; index > -1; index--) {
  28743. if (materials[index].id === id) {
  28744. this.material = materials[index];
  28745. return this;
  28746. }
  28747. }
  28748. // Multi
  28749. var multiMaterials = this.getScene().multiMaterials;
  28750. for (index = multiMaterials.length - 1; index > -1; index--) {
  28751. if (multiMaterials[index].id === id) {
  28752. this.material = multiMaterials[index];
  28753. return this;
  28754. }
  28755. }
  28756. return this;
  28757. };
  28758. /**
  28759. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28760. */
  28761. Mesh.prototype.getAnimatables = function () {
  28762. var results = new Array();
  28763. if (this.material) {
  28764. results.push(this.material);
  28765. }
  28766. if (this.skeleton) {
  28767. results.push(this.skeleton);
  28768. }
  28769. return results;
  28770. };
  28771. /**
  28772. * Modifies the mesh geometry according to the passed transformation matrix.
  28773. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28774. * The mesh normals are modified accordingly the same transformation.
  28775. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28776. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28777. * Returns the Mesh.
  28778. */
  28779. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28780. // Position
  28781. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28782. return this;
  28783. }
  28784. var submeshes = this.subMeshes.splice(0);
  28785. this._resetPointsArrayCache();
  28786. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28787. var temp = new Array();
  28788. var index;
  28789. for (index = 0; index < data.length; index += 3) {
  28790. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28791. }
  28792. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28793. // Normals
  28794. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28795. return this;
  28796. }
  28797. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28798. temp = [];
  28799. for (index = 0; index < data.length; index += 3) {
  28800. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28801. }
  28802. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28803. // flip faces?
  28804. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28805. this.flipFaces();
  28806. }
  28807. // Restore submeshes
  28808. this.releaseSubMeshes();
  28809. this.subMeshes = submeshes;
  28810. return this;
  28811. };
  28812. /**
  28813. * Modifies the mesh geometry according to its own current World Matrix.
  28814. * The mesh World Matrix is then reset.
  28815. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28816. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28817. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28818. * Returns the Mesh.
  28819. */
  28820. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28821. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28822. this.scaling.copyFromFloats(1, 1, 1);
  28823. this.position.copyFromFloats(0, 0, 0);
  28824. this.rotation.copyFromFloats(0, 0, 0);
  28825. //only if quaternion is already set
  28826. if (this.rotationQuaternion) {
  28827. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28828. }
  28829. this._worldMatrix = BABYLON.Matrix.Identity();
  28830. return this;
  28831. };
  28832. Object.defineProperty(Mesh.prototype, "_positions", {
  28833. // Cache
  28834. get: function () {
  28835. if (this._geometry) {
  28836. return this._geometry._positions;
  28837. }
  28838. return null;
  28839. },
  28840. enumerable: true,
  28841. configurable: true
  28842. });
  28843. Mesh.prototype._resetPointsArrayCache = function () {
  28844. if (this._geometry) {
  28845. this._geometry._resetPointsArrayCache();
  28846. }
  28847. return this;
  28848. };
  28849. Mesh.prototype._generatePointsArray = function () {
  28850. if (this._geometry) {
  28851. return this._geometry._generatePointsArray();
  28852. }
  28853. return false;
  28854. };
  28855. /**
  28856. * Returns a new Mesh object generated from the current mesh properties.
  28857. * This method must not get confused with createInstance().
  28858. * The parameter `name` is a string, the name given to the new mesh.
  28859. * The optional parameter `newParent` can be any Node object (default `null`).
  28860. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28861. * 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.
  28862. */
  28863. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28864. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28865. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28866. };
  28867. /**
  28868. * Releases resources associated with this mesh.
  28869. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  28870. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  28871. */
  28872. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28873. var _this = this;
  28874. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28875. this.morphTargetManager = null;
  28876. if (this._geometry) {
  28877. this._geometry.releaseForMesh(this, true);
  28878. }
  28879. // Sources
  28880. var meshes = this.getScene().meshes;
  28881. meshes.forEach(function (abstractMesh) {
  28882. var mesh = abstractMesh;
  28883. if (mesh._source && mesh._source === _this) {
  28884. mesh._source = null;
  28885. }
  28886. });
  28887. this._source = null;
  28888. // Instances
  28889. if (this._instancesBuffer) {
  28890. this._instancesBuffer.dispose();
  28891. this._instancesBuffer = null;
  28892. }
  28893. while (this.instances.length) {
  28894. this.instances[0].dispose();
  28895. }
  28896. // Effect layers.
  28897. var effectLayers = this.getScene().effectLayers;
  28898. for (var i = 0; i < effectLayers.length; i++) {
  28899. var effectLayer = effectLayers[i];
  28900. if (effectLayer) {
  28901. effectLayer._disposeMesh(this);
  28902. }
  28903. }
  28904. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28905. };
  28906. /**
  28907. * Modifies the mesh geometry according to a displacement map.
  28908. * 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.
  28909. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28910. * This method returns nothing.
  28911. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28912. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28913. * 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.
  28914. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28915. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28916. *
  28917. * Returns the Mesh.
  28918. */
  28919. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28920. var _this = this;
  28921. var scene = this.getScene();
  28922. var onload = function (img) {
  28923. // Getting height map data
  28924. var canvas = document.createElement("canvas");
  28925. var context = canvas.getContext("2d");
  28926. var heightMapWidth = img.width;
  28927. var heightMapHeight = img.height;
  28928. canvas.width = heightMapWidth;
  28929. canvas.height = heightMapHeight;
  28930. context.drawImage(img, 0, 0);
  28931. // Create VertexData from map data
  28932. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28933. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28934. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28935. //execute success callback, if set
  28936. if (onSuccess) {
  28937. onSuccess(_this);
  28938. }
  28939. };
  28940. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28941. return this;
  28942. };
  28943. /**
  28944. * Modifies the mesh geometry according to a displacementMap buffer.
  28945. * 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.
  28946. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28947. * This method returns nothing.
  28948. * 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.
  28949. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28950. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28951. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28952. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28953. *
  28954. * Returns the Mesh.
  28955. */
  28956. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28957. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28958. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28959. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28960. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28961. return this;
  28962. }
  28963. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28964. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28965. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28966. var position = BABYLON.Vector3.Zero();
  28967. var normal = BABYLON.Vector3.Zero();
  28968. var uv = BABYLON.Vector2.Zero();
  28969. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28970. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28971. for (var index = 0; index < positions.length; index += 3) {
  28972. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28973. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28974. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28975. // Compute height
  28976. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28977. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28978. var pos = (u + v * heightMapWidth) * 4;
  28979. var r = buffer[pos] / 255.0;
  28980. var g = buffer[pos + 1] / 255.0;
  28981. var b = buffer[pos + 2] / 255.0;
  28982. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28983. normal.normalize();
  28984. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28985. position = position.add(normal);
  28986. position.toArray(positions, index);
  28987. }
  28988. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28989. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28990. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28991. return this;
  28992. };
  28993. /**
  28994. * Modify the mesh to get a flat shading rendering.
  28995. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28996. * This method returns the Mesh.
  28997. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28998. */
  28999. Mesh.prototype.convertToFlatShadedMesh = function () {
  29000. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29001. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29002. var kinds = this.getVerticesDataKinds();
  29003. var vbs = {};
  29004. var data = {};
  29005. var newdata = {};
  29006. var updatableNormals = false;
  29007. var kindIndex;
  29008. var kind;
  29009. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29010. kind = kinds[kindIndex];
  29011. var vertexBuffer = this.getVertexBuffer(kind);
  29012. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29013. updatableNormals = vertexBuffer.isUpdatable();
  29014. kinds.splice(kindIndex, 1);
  29015. kindIndex--;
  29016. continue;
  29017. }
  29018. vbs[kind] = vertexBuffer;
  29019. data[kind] = vbs[kind].getData();
  29020. newdata[kind] = [];
  29021. }
  29022. // Save previous submeshes
  29023. var previousSubmeshes = this.subMeshes.slice(0);
  29024. var indices = this.getIndices();
  29025. var totalIndices = this.getTotalIndices();
  29026. // Generating unique vertices per face
  29027. var index;
  29028. for (index = 0; index < totalIndices; index++) {
  29029. var vertexIndex = indices[index];
  29030. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29031. kind = kinds[kindIndex];
  29032. var stride = vbs[kind].getStrideSize();
  29033. for (var offset = 0; offset < stride; offset++) {
  29034. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29035. }
  29036. }
  29037. }
  29038. // Updating faces & normal
  29039. var normals = [];
  29040. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29041. for (index = 0; index < totalIndices; index += 3) {
  29042. indices[index] = index;
  29043. indices[index + 1] = index + 1;
  29044. indices[index + 2] = index + 2;
  29045. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29046. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29047. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29048. var p1p2 = p1.subtract(p2);
  29049. var p3p2 = p3.subtract(p2);
  29050. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29051. // Store same normals for every vertex
  29052. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29053. normals.push(normal.x);
  29054. normals.push(normal.y);
  29055. normals.push(normal.z);
  29056. }
  29057. }
  29058. this.setIndices(indices);
  29059. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29060. // Updating vertex buffers
  29061. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29062. kind = kinds[kindIndex];
  29063. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29064. }
  29065. // Updating submeshes
  29066. this.releaseSubMeshes();
  29067. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29068. var previousOne = previousSubmeshes[submeshIndex];
  29069. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29070. }
  29071. this.synchronizeInstances();
  29072. return this;
  29073. };
  29074. /**
  29075. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29076. * In other words, more vertices, no more indices and a single bigger VBO.
  29077. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29078. * Returns the Mesh.
  29079. */
  29080. Mesh.prototype.convertToUnIndexedMesh = function () {
  29081. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29082. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29083. var kinds = this.getVerticesDataKinds();
  29084. var vbs = {};
  29085. var data = {};
  29086. var newdata = {};
  29087. var kindIndex;
  29088. var kind;
  29089. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29090. kind = kinds[kindIndex];
  29091. var vertexBuffer = this.getVertexBuffer(kind);
  29092. vbs[kind] = vertexBuffer;
  29093. data[kind] = vbs[kind].getData();
  29094. newdata[kind] = [];
  29095. }
  29096. // Save previous submeshes
  29097. var previousSubmeshes = this.subMeshes.slice(0);
  29098. var indices = this.getIndices();
  29099. var totalIndices = this.getTotalIndices();
  29100. // Generating unique vertices per face
  29101. var index;
  29102. for (index = 0; index < totalIndices; index++) {
  29103. var vertexIndex = indices[index];
  29104. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29105. kind = kinds[kindIndex];
  29106. var stride = vbs[kind].getStrideSize();
  29107. for (var offset = 0; offset < stride; offset++) {
  29108. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29109. }
  29110. }
  29111. }
  29112. // Updating indices
  29113. for (index = 0; index < totalIndices; index += 3) {
  29114. indices[index] = index;
  29115. indices[index + 1] = index + 1;
  29116. indices[index + 2] = index + 2;
  29117. }
  29118. this.setIndices(indices);
  29119. // Updating vertex buffers
  29120. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29121. kind = kinds[kindIndex];
  29122. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29123. }
  29124. // Updating submeshes
  29125. this.releaseSubMeshes();
  29126. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29127. var previousOne = previousSubmeshes[submeshIndex];
  29128. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29129. }
  29130. this._unIndexed = true;
  29131. this.synchronizeInstances();
  29132. return this;
  29133. };
  29134. /**
  29135. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29136. * This method returns the Mesh.
  29137. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29138. */
  29139. Mesh.prototype.flipFaces = function (flipNormals) {
  29140. if (flipNormals === void 0) { flipNormals = false; }
  29141. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29142. var i;
  29143. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29144. for (i = 0; i < vertex_data.normals.length; i++) {
  29145. vertex_data.normals[i] *= -1;
  29146. }
  29147. }
  29148. if (vertex_data.indices) {
  29149. var temp;
  29150. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29151. // reassign indices
  29152. temp = vertex_data.indices[i + 1];
  29153. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29154. vertex_data.indices[i + 2] = temp;
  29155. }
  29156. }
  29157. vertex_data.applyToMesh(this);
  29158. return this;
  29159. };
  29160. // Instances
  29161. /**
  29162. * Creates a new InstancedMesh object from the mesh model.
  29163. * An instance shares the same properties and the same material than its model.
  29164. * Only these properties of each instance can then be set individually :
  29165. * - position
  29166. * - rotation
  29167. * - rotationQuaternion
  29168. * - setPivotMatrix
  29169. * - scaling
  29170. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29171. * Warning : this method is not supported for Line mesh and LineSystem
  29172. */
  29173. Mesh.prototype.createInstance = function (name) {
  29174. return new BABYLON.InstancedMesh(name, this);
  29175. };
  29176. /**
  29177. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29178. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29179. * This method returns the Mesh.
  29180. */
  29181. Mesh.prototype.synchronizeInstances = function () {
  29182. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29183. var instance = this.instances[instanceIndex];
  29184. instance._syncSubMeshes();
  29185. }
  29186. return this;
  29187. };
  29188. /**
  29189. * Simplify the mesh according to the given array of settings.
  29190. * Function will return immediately and will simplify async. It returns the Mesh.
  29191. * @param settings a collection of simplification settings.
  29192. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29193. * @param type the type of simplification to run.
  29194. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29195. */
  29196. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29197. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29198. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29199. this.getScene().simplificationQueue.addTask({
  29200. settings: settings,
  29201. parallelProcessing: parallelProcessing,
  29202. mesh: this,
  29203. simplificationType: simplificationType,
  29204. successCallback: successCallback
  29205. });
  29206. return this;
  29207. };
  29208. /**
  29209. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29210. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29211. * This should be used together with the simplification to avoid disappearing triangles.
  29212. * Returns the Mesh.
  29213. * @param successCallback an optional success callback to be called after the optimization finished.
  29214. */
  29215. Mesh.prototype.optimizeIndices = function (successCallback) {
  29216. var _this = this;
  29217. var indices = this.getIndices();
  29218. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29219. if (!positions || !indices) {
  29220. return this;
  29221. }
  29222. var vectorPositions = new Array();
  29223. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29224. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29225. }
  29226. var dupes = new Array();
  29227. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29228. var realPos = vectorPositions.length - 1 - iteration;
  29229. var testedPosition = vectorPositions[realPos];
  29230. for (var j = 0; j < realPos; ++j) {
  29231. var againstPosition = vectorPositions[j];
  29232. if (testedPosition.equals(againstPosition)) {
  29233. dupes[realPos] = j;
  29234. break;
  29235. }
  29236. }
  29237. }, function () {
  29238. for (var i = 0; i < indices.length; ++i) {
  29239. indices[i] = dupes[indices[i]] || indices[i];
  29240. }
  29241. //indices are now reordered
  29242. var originalSubMeshes = _this.subMeshes.slice(0);
  29243. _this.setIndices(indices);
  29244. _this.subMeshes = originalSubMeshes;
  29245. if (successCallback) {
  29246. successCallback(_this);
  29247. }
  29248. });
  29249. return this;
  29250. };
  29251. Mesh.prototype.serialize = function (serializationObject) {
  29252. serializationObject.name = this.name;
  29253. serializationObject.id = this.id;
  29254. serializationObject.type = this.getClassName();
  29255. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29256. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29257. }
  29258. serializationObject.position = this.position.asArray();
  29259. if (this.rotationQuaternion) {
  29260. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29261. }
  29262. else if (this.rotation) {
  29263. serializationObject.rotation = this.rotation.asArray();
  29264. }
  29265. serializationObject.scaling = this.scaling.asArray();
  29266. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29267. serializationObject.isEnabled = this.isEnabled(false);
  29268. serializationObject.isVisible = this.isVisible;
  29269. serializationObject.infiniteDistance = this.infiniteDistance;
  29270. serializationObject.pickable = this.isPickable;
  29271. serializationObject.receiveShadows = this.receiveShadows;
  29272. serializationObject.billboardMode = this.billboardMode;
  29273. serializationObject.visibility = this.visibility;
  29274. serializationObject.checkCollisions = this.checkCollisions;
  29275. serializationObject.isBlocker = this.isBlocker;
  29276. // Parent
  29277. if (this.parent) {
  29278. serializationObject.parentId = this.parent.id;
  29279. }
  29280. // Geometry
  29281. serializationObject.isUnIndexed = this.isUnIndexed;
  29282. var geometry = this._geometry;
  29283. if (geometry) {
  29284. var geometryId = geometry.id;
  29285. serializationObject.geometryId = geometryId;
  29286. // SubMeshes
  29287. serializationObject.subMeshes = [];
  29288. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29289. var subMesh = this.subMeshes[subIndex];
  29290. serializationObject.subMeshes.push({
  29291. materialIndex: subMesh.materialIndex,
  29292. verticesStart: subMesh.verticesStart,
  29293. verticesCount: subMesh.verticesCount,
  29294. indexStart: subMesh.indexStart,
  29295. indexCount: subMesh.indexCount
  29296. });
  29297. }
  29298. }
  29299. // Material
  29300. if (this.material) {
  29301. serializationObject.materialId = this.material.id;
  29302. }
  29303. else {
  29304. this.material = null;
  29305. }
  29306. // Morph targets
  29307. if (this.morphTargetManager) {
  29308. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29309. }
  29310. // Skeleton
  29311. if (this.skeleton) {
  29312. serializationObject.skeletonId = this.skeleton.id;
  29313. }
  29314. // Physics
  29315. //TODO implement correct serialization for physics impostors.
  29316. var impostor = this.getPhysicsImpostor();
  29317. if (impostor) {
  29318. serializationObject.physicsMass = impostor.getParam("mass");
  29319. serializationObject.physicsFriction = impostor.getParam("friction");
  29320. serializationObject.physicsRestitution = impostor.getParam("mass");
  29321. serializationObject.physicsImpostor = impostor.type;
  29322. }
  29323. // Metadata
  29324. if (this.metadata) {
  29325. serializationObject.metadata = this.metadata;
  29326. }
  29327. // Instances
  29328. serializationObject.instances = [];
  29329. for (var index = 0; index < this.instances.length; index++) {
  29330. var instance = this.instances[index];
  29331. var serializationInstance = {
  29332. name: instance.name,
  29333. id: instance.id,
  29334. position: instance.position.asArray(),
  29335. scaling: instance.scaling.asArray()
  29336. };
  29337. if (instance.rotationQuaternion) {
  29338. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29339. }
  29340. else if (instance.rotation) {
  29341. serializationInstance.rotation = instance.rotation.asArray();
  29342. }
  29343. serializationObject.instances.push(serializationInstance);
  29344. // Animations
  29345. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29346. serializationInstance.ranges = instance.serializeAnimationRanges();
  29347. }
  29348. //
  29349. // Animations
  29350. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29351. serializationObject.ranges = this.serializeAnimationRanges();
  29352. // Layer mask
  29353. serializationObject.layerMask = this.layerMask;
  29354. // Alpha
  29355. serializationObject.alphaIndex = this.alphaIndex;
  29356. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29357. // Overlay
  29358. serializationObject.overlayAlpha = this.overlayAlpha;
  29359. serializationObject.overlayColor = this.overlayColor.asArray();
  29360. serializationObject.renderOverlay = this.renderOverlay;
  29361. // Fog
  29362. serializationObject.applyFog = this.applyFog;
  29363. // Action Manager
  29364. if (this.actionManager) {
  29365. serializationObject.actions = this.actionManager.serialize(this.name);
  29366. }
  29367. };
  29368. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29369. if (!this.geometry) {
  29370. return;
  29371. }
  29372. this._markSubMeshesAsAttributesDirty();
  29373. var morphTargetManager = this._morphTargetManager;
  29374. if (morphTargetManager && morphTargetManager.vertexCount) {
  29375. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29376. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29377. this.morphTargetManager = null;
  29378. return;
  29379. }
  29380. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29381. var morphTarget = morphTargetManager.getActiveTarget(index);
  29382. var positions = morphTarget.getPositions();
  29383. if (!positions) {
  29384. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29385. return;
  29386. }
  29387. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29388. var normals = morphTarget.getNormals();
  29389. if (normals) {
  29390. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29391. }
  29392. var tangents = morphTarget.getTangents();
  29393. if (tangents) {
  29394. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29395. }
  29396. }
  29397. }
  29398. else {
  29399. var index = 0;
  29400. // Positions
  29401. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29402. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29403. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29404. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29405. }
  29406. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29407. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29408. }
  29409. index++;
  29410. }
  29411. }
  29412. };
  29413. // Statics
  29414. /**
  29415. * Returns a new Mesh object parsed from the source provided.
  29416. * The parameter `parsedMesh` is the source.
  29417. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29418. */
  29419. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29420. var mesh;
  29421. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29422. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29423. }
  29424. else {
  29425. mesh = new Mesh(parsedMesh.name, scene);
  29426. }
  29427. mesh.id = parsedMesh.id;
  29428. if (BABYLON.Tags) {
  29429. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29430. }
  29431. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29432. if (parsedMesh.metadata !== undefined) {
  29433. mesh.metadata = parsedMesh.metadata;
  29434. }
  29435. if (parsedMesh.rotationQuaternion) {
  29436. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29437. }
  29438. else if (parsedMesh.rotation) {
  29439. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29440. }
  29441. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29442. if (parsedMesh.localMatrix) {
  29443. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29444. }
  29445. else if (parsedMesh.pivotMatrix) {
  29446. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29447. }
  29448. mesh.setEnabled(parsedMesh.isEnabled);
  29449. mesh.isVisible = parsedMesh.isVisible;
  29450. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29451. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29452. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29453. if (parsedMesh.applyFog !== undefined) {
  29454. mesh.applyFog = parsedMesh.applyFog;
  29455. }
  29456. if (parsedMesh.pickable !== undefined) {
  29457. mesh.isPickable = parsedMesh.pickable;
  29458. }
  29459. if (parsedMesh.alphaIndex !== undefined) {
  29460. mesh.alphaIndex = parsedMesh.alphaIndex;
  29461. }
  29462. mesh.receiveShadows = parsedMesh.receiveShadows;
  29463. mesh.billboardMode = parsedMesh.billboardMode;
  29464. if (parsedMesh.visibility !== undefined) {
  29465. mesh.visibility = parsedMesh.visibility;
  29466. }
  29467. mesh.checkCollisions = parsedMesh.checkCollisions;
  29468. if (parsedMesh.isBlocker !== undefined) {
  29469. mesh.isBlocker = parsedMesh.isBlocker;
  29470. }
  29471. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29472. // freezeWorldMatrix
  29473. if (parsedMesh.freezeWorldMatrix) {
  29474. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29475. }
  29476. // Parent
  29477. if (parsedMesh.parentId) {
  29478. mesh._waitingParentId = parsedMesh.parentId;
  29479. }
  29480. // Actions
  29481. if (parsedMesh.actions !== undefined) {
  29482. mesh._waitingActions = parsedMesh.actions;
  29483. }
  29484. // Overlay
  29485. if (parsedMesh.overlayAlpha !== undefined) {
  29486. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29487. }
  29488. if (parsedMesh.overlayColor !== undefined) {
  29489. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29490. }
  29491. if (parsedMesh.renderOverlay !== undefined) {
  29492. mesh.renderOverlay = parsedMesh.renderOverlay;
  29493. }
  29494. // Geometry
  29495. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29496. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29497. if (parsedMesh.delayLoadingFile) {
  29498. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29499. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29500. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29501. if (parsedMesh._binaryInfo) {
  29502. mesh._binaryInfo = parsedMesh._binaryInfo;
  29503. }
  29504. mesh._delayInfo = [];
  29505. if (parsedMesh.hasUVs) {
  29506. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29507. }
  29508. if (parsedMesh.hasUVs2) {
  29509. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29510. }
  29511. if (parsedMesh.hasUVs3) {
  29512. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29513. }
  29514. if (parsedMesh.hasUVs4) {
  29515. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29516. }
  29517. if (parsedMesh.hasUVs5) {
  29518. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29519. }
  29520. if (parsedMesh.hasUVs6) {
  29521. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29522. }
  29523. if (parsedMesh.hasColors) {
  29524. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29525. }
  29526. if (parsedMesh.hasMatricesIndices) {
  29527. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29528. }
  29529. if (parsedMesh.hasMatricesWeights) {
  29530. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29531. }
  29532. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29533. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29534. mesh._checkDelayState();
  29535. }
  29536. }
  29537. else {
  29538. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29539. }
  29540. // Material
  29541. if (parsedMesh.materialId) {
  29542. mesh.setMaterialByID(parsedMesh.materialId);
  29543. }
  29544. else {
  29545. mesh.material = null;
  29546. }
  29547. // Morph targets
  29548. if (parsedMesh.morphTargetManagerId > -1) {
  29549. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29550. }
  29551. // Skeleton
  29552. if (parsedMesh.skeletonId > -1) {
  29553. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29554. if (parsedMesh.numBoneInfluencers) {
  29555. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29556. }
  29557. }
  29558. // Animations
  29559. if (parsedMesh.animations) {
  29560. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29561. var parsedAnimation = parsedMesh.animations[animationIndex];
  29562. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29563. }
  29564. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29565. }
  29566. if (parsedMesh.autoAnimate) {
  29567. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29568. }
  29569. // Layer Mask
  29570. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29571. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29572. }
  29573. else {
  29574. mesh.layerMask = 0x0FFFFFFF;
  29575. }
  29576. // Physics
  29577. if (parsedMesh.physicsImpostor) {
  29578. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29579. mass: parsedMesh.physicsMass,
  29580. friction: parsedMesh.physicsFriction,
  29581. restitution: parsedMesh.physicsRestitution
  29582. }, scene);
  29583. }
  29584. // Instances
  29585. if (parsedMesh.instances) {
  29586. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29587. var parsedInstance = parsedMesh.instances[index];
  29588. var instance = mesh.createInstance(parsedInstance.name);
  29589. if (parsedInstance.id) {
  29590. instance.id = parsedInstance.id;
  29591. }
  29592. if (BABYLON.Tags) {
  29593. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29594. }
  29595. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29596. if (parsedInstance.parentId) {
  29597. instance._waitingParentId = parsedInstance.parentId;
  29598. }
  29599. if (parsedInstance.rotationQuaternion) {
  29600. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29601. }
  29602. else if (parsedInstance.rotation) {
  29603. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29604. }
  29605. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29606. instance.checkCollisions = mesh.checkCollisions;
  29607. if (parsedMesh.animations) {
  29608. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29609. parsedAnimation = parsedMesh.animations[animationIndex];
  29610. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29611. }
  29612. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29613. }
  29614. }
  29615. }
  29616. return mesh;
  29617. };
  29618. /**
  29619. * Creates a ribbon mesh.
  29620. * Please consider using the same method from the MeshBuilder class instead.
  29621. * 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.
  29622. *
  29623. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29624. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29625. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29626. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29627. * 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.
  29628. * 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.
  29629. * 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
  29630. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29631. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29632. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29633. */
  29634. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29635. if (closeArray === void 0) { closeArray = false; }
  29636. if (updatable === void 0) { updatable = false; }
  29637. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29638. pathArray: pathArray,
  29639. closeArray: closeArray,
  29640. closePath: closePath,
  29641. offset: offset,
  29642. updatable: updatable,
  29643. sideOrientation: sideOrientation,
  29644. instance: instance
  29645. }, scene);
  29646. };
  29647. /**
  29648. * Creates a plane polygonal mesh. By default, this is a disc.
  29649. * Please consider using the same method from the MeshBuilder class instead.
  29650. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29651. * 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.
  29652. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29653. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29654. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29655. */
  29656. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29657. if (scene === void 0) { scene = null; }
  29658. var options = {
  29659. radius: radius,
  29660. tessellation: tessellation,
  29661. sideOrientation: sideOrientation,
  29662. updatable: updatable
  29663. };
  29664. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29665. };
  29666. /**
  29667. * Creates a box mesh.
  29668. * Please consider using the same method from the MeshBuilder class instead.
  29669. * The parameter `size` sets the size (float) of each box side (default 1).
  29670. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29671. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29672. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29673. */
  29674. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29675. if (scene === void 0) { scene = null; }
  29676. var options = {
  29677. size: size,
  29678. sideOrientation: sideOrientation,
  29679. updatable: updatable
  29680. };
  29681. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29682. };
  29683. /**
  29684. * Creates a sphere mesh.
  29685. * Please consider using the same method from the MeshBuilder class instead.
  29686. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29687. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29688. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29689. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29690. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29691. */
  29692. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29693. var options = {
  29694. segments: segments,
  29695. diameterX: diameter,
  29696. diameterY: diameter,
  29697. diameterZ: diameter,
  29698. sideOrientation: sideOrientation,
  29699. updatable: updatable
  29700. };
  29701. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29702. };
  29703. /**
  29704. * Creates a cylinder or a cone mesh.
  29705. * Please consider using the same method from the MeshBuilder class instead.
  29706. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29707. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29708. * 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.
  29709. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29710. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29711. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29712. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29713. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29714. */
  29715. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29716. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29717. if (scene !== undefined) {
  29718. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29719. updatable = scene;
  29720. }
  29721. scene = subdivisions;
  29722. subdivisions = 1;
  29723. }
  29724. var options = {
  29725. height: height,
  29726. diameterTop: diameterTop,
  29727. diameterBottom: diameterBottom,
  29728. tessellation: tessellation,
  29729. subdivisions: subdivisions,
  29730. sideOrientation: sideOrientation,
  29731. updatable: updatable
  29732. };
  29733. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29734. };
  29735. // Torus (Code from SharpDX.org)
  29736. /**
  29737. * Creates a torus mesh.
  29738. * Please consider using the same method from the MeshBuilder class instead.
  29739. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29740. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29741. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29742. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29743. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29744. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29745. */
  29746. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29747. var options = {
  29748. diameter: diameter,
  29749. thickness: thickness,
  29750. tessellation: tessellation,
  29751. sideOrientation: sideOrientation,
  29752. updatable: updatable
  29753. };
  29754. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29755. };
  29756. /**
  29757. * Creates a torus knot mesh.
  29758. * Please consider using the same method from the MeshBuilder class instead.
  29759. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29760. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29761. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29762. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29763. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29764. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29765. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29766. */
  29767. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29768. var options = {
  29769. radius: radius,
  29770. tube: tube,
  29771. radialSegments: radialSegments,
  29772. tubularSegments: tubularSegments,
  29773. p: p,
  29774. q: q,
  29775. sideOrientation: sideOrientation,
  29776. updatable: updatable
  29777. };
  29778. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29779. };
  29780. /**
  29781. * Creates a line mesh.
  29782. * Please consider using the same method from the MeshBuilder class instead.
  29783. * 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.
  29784. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29785. * The parameter `points` is an array successive Vector3.
  29786. * 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
  29787. * When updating an instance, remember that only point positions can change, not the number of points.
  29788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29789. */
  29790. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29791. if (scene === void 0) { scene = null; }
  29792. if (updatable === void 0) { updatable = false; }
  29793. if (instance === void 0) { instance = null; }
  29794. var options = {
  29795. points: points,
  29796. updatable: updatable,
  29797. instance: instance
  29798. };
  29799. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29800. };
  29801. /**
  29802. * Creates a dashed line mesh.
  29803. * Please consider using the same method from the MeshBuilder class instead.
  29804. * 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.
  29805. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29806. * The parameter `points` is an array successive Vector3.
  29807. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29808. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29809. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29810. * 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
  29811. * When updating an instance, remember that only point positions can change, not the number of points.
  29812. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29813. */
  29814. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29815. if (scene === void 0) { scene = null; }
  29816. var options = {
  29817. points: points,
  29818. dashSize: dashSize,
  29819. gapSize: gapSize,
  29820. dashNb: dashNb,
  29821. updatable: updatable,
  29822. instance: instance
  29823. };
  29824. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29825. };
  29826. /**
  29827. * Creates a polygon mesh.
  29828. * Please consider using the same method from the MeshBuilder class instead.
  29829. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29830. * 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.
  29831. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29832. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29833. * Remember you can only change the shape positions, not their number when updating a polygon.
  29834. */
  29835. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29836. var options = {
  29837. shape: shape,
  29838. holes: holes,
  29839. updatable: updatable,
  29840. sideOrientation: sideOrientation
  29841. };
  29842. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29843. };
  29844. /**
  29845. * Creates an extruded polygon mesh, with depth in the Y direction.
  29846. * Please consider using the same method from the MeshBuilder class instead.
  29847. */
  29848. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29849. var options = {
  29850. shape: shape,
  29851. holes: holes,
  29852. depth: depth,
  29853. updatable: updatable,
  29854. sideOrientation: sideOrientation
  29855. };
  29856. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29857. };
  29858. /**
  29859. * Creates an extruded shape mesh.
  29860. * 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.
  29861. * Please consider using the same method from the MeshBuilder class instead.
  29862. *
  29863. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29864. * 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
  29865. * extruded along the Z axis.
  29866. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29867. * 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.
  29868. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29869. * 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
  29870. * 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
  29871. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29872. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29873. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29874. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29875. */
  29876. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29877. if (scene === void 0) { scene = null; }
  29878. var options = {
  29879. shape: shape,
  29880. path: path,
  29881. scale: scale,
  29882. rotation: rotation,
  29883. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29884. sideOrientation: sideOrientation,
  29885. instance: instance,
  29886. updatable: updatable
  29887. };
  29888. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29889. };
  29890. /**
  29891. * Creates an custom extruded shape mesh.
  29892. * 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.
  29893. * Please consider using the same method from the MeshBuilder class instead.
  29894. *
  29895. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29896. * 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
  29897. * extruded along the Z axis.
  29898. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29899. * 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
  29900. * and the distance of this point from the begining of the path :
  29901. * ```javascript
  29902. * var rotationFunction = function(i, distance) {
  29903. * // do things
  29904. * return rotationValue; }
  29905. * ```
  29906. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29907. * 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
  29908. * and the distance of this point from the begining of the path :
  29909. * ```javascript
  29910. * var scaleFunction = function(i, distance) {
  29911. * // do things
  29912. * return scaleValue;}
  29913. * ```
  29914. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29915. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29916. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29917. * 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
  29918. * 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
  29919. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29920. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29921. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29923. */
  29924. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29925. var options = {
  29926. shape: shape,
  29927. path: path,
  29928. scaleFunction: scaleFunction,
  29929. rotationFunction: rotationFunction,
  29930. ribbonCloseArray: ribbonCloseArray,
  29931. ribbonClosePath: ribbonClosePath,
  29932. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29933. sideOrientation: sideOrientation,
  29934. instance: instance,
  29935. updatable: updatable
  29936. };
  29937. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29938. };
  29939. /**
  29940. * Creates lathe mesh.
  29941. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29942. * Please consider using the same method from the MeshBuilder class instead.
  29943. * 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
  29944. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29945. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29946. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29947. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29948. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29949. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29950. */
  29951. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29952. var options = {
  29953. shape: shape,
  29954. radius: radius,
  29955. tessellation: tessellation,
  29956. sideOrientation: sideOrientation,
  29957. updatable: updatable
  29958. };
  29959. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29960. };
  29961. /**
  29962. * Creates a plane mesh.
  29963. * Please consider using the same method from the MeshBuilder class instead.
  29964. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29965. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29966. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29967. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29968. */
  29969. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29970. var options = {
  29971. size: size,
  29972. width: size,
  29973. height: size,
  29974. sideOrientation: sideOrientation,
  29975. updatable: updatable
  29976. };
  29977. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29978. };
  29979. /**
  29980. * Creates a ground mesh.
  29981. * Please consider using the same method from the MeshBuilder class instead.
  29982. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29983. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29984. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29985. */
  29986. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29987. var options = {
  29988. width: width,
  29989. height: height,
  29990. subdivisions: subdivisions,
  29991. updatable: updatable
  29992. };
  29993. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29994. };
  29995. /**
  29996. * Creates a tiled ground mesh.
  29997. * Please consider using the same method from the MeshBuilder class instead.
  29998. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29999. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30000. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30001. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30002. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30003. * numbers of subdivisions on the ground width and height of each tile.
  30004. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30005. */
  30006. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30007. var options = {
  30008. xmin: xmin,
  30009. zmin: zmin,
  30010. xmax: xmax,
  30011. zmax: zmax,
  30012. subdivisions: subdivisions,
  30013. precision: precision,
  30014. updatable: updatable
  30015. };
  30016. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30017. };
  30018. /**
  30019. * Creates a ground mesh from a height map.
  30020. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30021. * Please consider using the same method from the MeshBuilder class instead.
  30022. * The parameter `url` sets the URL of the height map image resource.
  30023. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30024. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30025. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30026. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30027. * 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).
  30028. * This function is passed the newly built mesh :
  30029. * ```javascript
  30030. * function(mesh) { // do things
  30031. * return; }
  30032. * ```
  30033. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30034. */
  30035. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30036. var options = {
  30037. width: width,
  30038. height: height,
  30039. subdivisions: subdivisions,
  30040. minHeight: minHeight,
  30041. maxHeight: maxHeight,
  30042. updatable: updatable,
  30043. onReady: onReady
  30044. };
  30045. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30046. };
  30047. /**
  30048. * Creates a tube mesh.
  30049. * 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.
  30050. * Please consider using the same method from the MeshBuilder class instead.
  30051. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30052. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30053. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30054. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30055. * 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.
  30056. * It must return a radius value (positive float) :
  30057. * ```javascript
  30058. * var radiusFunction = function(i, distance) {
  30059. * // do things
  30060. * return radius; }
  30061. * ```
  30062. * 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
  30063. * 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
  30064. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30065. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30066. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30067. */
  30068. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30069. var options = {
  30070. path: path,
  30071. radius: radius,
  30072. tessellation: tessellation,
  30073. radiusFunction: radiusFunction,
  30074. arc: 1,
  30075. cap: cap,
  30076. updatable: updatable,
  30077. sideOrientation: sideOrientation,
  30078. instance: instance
  30079. };
  30080. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30081. };
  30082. /**
  30083. * Creates a polyhedron mesh.
  30084. * Please consider using the same method from the MeshBuilder class instead.
  30085. * 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
  30086. * to choose the wanted type.
  30087. * The parameter `size` (positive float, default 1) sets the polygon size.
  30088. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30089. * 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`.
  30090. * 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
  30091. * 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)`).
  30092. * 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
  30093. * 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.
  30094. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30095. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30096. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30097. */
  30098. Mesh.CreatePolyhedron = function (name, options, scene) {
  30099. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30100. };
  30101. /**
  30102. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30103. * Please consider using the same method from the MeshBuilder class instead.
  30104. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30105. * 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`).
  30106. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30107. * 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.
  30108. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30109. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30110. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30111. */
  30112. Mesh.CreateIcoSphere = function (name, options, scene) {
  30113. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30114. };
  30115. /**
  30116. * Creates a decal mesh.
  30117. * Please consider using the same method from the MeshBuilder class instead.
  30118. * 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.
  30119. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30120. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30121. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30122. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30123. */
  30124. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30125. var options = {
  30126. position: position,
  30127. normal: normal,
  30128. size: size,
  30129. angle: angle
  30130. };
  30131. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30132. };
  30133. // Skeletons
  30134. /**
  30135. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30136. */
  30137. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30138. if (!this._sourcePositions) {
  30139. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30140. if (!source) {
  30141. return this._sourcePositions;
  30142. }
  30143. this._sourcePositions = new Float32Array(source);
  30144. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30145. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30146. }
  30147. }
  30148. return this._sourcePositions;
  30149. };
  30150. /**
  30151. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30152. */
  30153. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30154. if (!this._sourceNormals) {
  30155. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30156. if (!source) {
  30157. return this._sourceNormals;
  30158. }
  30159. this._sourceNormals = new Float32Array(source);
  30160. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30161. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30162. }
  30163. }
  30164. return this._sourceNormals;
  30165. };
  30166. /**
  30167. * Updates the vertex buffer by applying transformation from the bones.
  30168. * Returns the Mesh.
  30169. *
  30170. * @param {skeleton} skeleton to apply
  30171. */
  30172. Mesh.prototype.applySkeleton = function (skeleton) {
  30173. if (!this.geometry) {
  30174. return this;
  30175. }
  30176. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30177. return this;
  30178. }
  30179. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30180. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30181. return this;
  30182. }
  30183. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30184. return this;
  30185. }
  30186. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30187. return this;
  30188. }
  30189. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30190. return this;
  30191. }
  30192. if (!this._sourcePositions) {
  30193. var submeshes = this.subMeshes.slice();
  30194. this.setPositionsForCPUSkinning();
  30195. this.subMeshes = submeshes;
  30196. }
  30197. if (!this._sourceNormals) {
  30198. this.setNormalsForCPUSkinning();
  30199. }
  30200. // positionsData checks for not being Float32Array will only pass at most once
  30201. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30202. if (!positionsData) {
  30203. return this;
  30204. }
  30205. if (!(positionsData instanceof Float32Array)) {
  30206. positionsData = new Float32Array(positionsData);
  30207. }
  30208. // normalsData checks for not being Float32Array will only pass at most once
  30209. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30210. if (!normalsData) {
  30211. return this;
  30212. }
  30213. if (!(normalsData instanceof Float32Array)) {
  30214. normalsData = new Float32Array(normalsData);
  30215. }
  30216. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30217. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30218. if (!matricesWeightsData || !matricesIndicesData) {
  30219. return this;
  30220. }
  30221. var needExtras = this.numBoneInfluencers > 4;
  30222. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30223. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30224. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30225. var tempVector3 = BABYLON.Vector3.Zero();
  30226. var finalMatrix = new BABYLON.Matrix();
  30227. var tempMatrix = new BABYLON.Matrix();
  30228. var matWeightIdx = 0;
  30229. var inf;
  30230. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30231. var weight;
  30232. for (inf = 0; inf < 4; inf++) {
  30233. weight = matricesWeightsData[matWeightIdx + inf];
  30234. if (weight > 0) {
  30235. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30236. finalMatrix.addToSelf(tempMatrix);
  30237. }
  30238. else
  30239. break;
  30240. }
  30241. if (needExtras) {
  30242. for (inf = 0; inf < 4; inf++) {
  30243. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30244. if (weight > 0) {
  30245. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30246. finalMatrix.addToSelf(tempMatrix);
  30247. }
  30248. else
  30249. break;
  30250. }
  30251. }
  30252. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30253. tempVector3.toArray(positionsData, index);
  30254. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30255. tempVector3.toArray(normalsData, index);
  30256. finalMatrix.reset();
  30257. }
  30258. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30259. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30260. return this;
  30261. };
  30262. // Tools
  30263. /**
  30264. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30265. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30266. */
  30267. Mesh.MinMax = function (meshes) {
  30268. var minVector = null;
  30269. var maxVector = null;
  30270. meshes.forEach(function (mesh, index, array) {
  30271. var boundingInfo = mesh.getBoundingInfo();
  30272. var boundingBox = boundingInfo.boundingBox;
  30273. if (!minVector || !maxVector) {
  30274. minVector = boundingBox.minimumWorld;
  30275. maxVector = boundingBox.maximumWorld;
  30276. }
  30277. else {
  30278. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30279. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30280. }
  30281. });
  30282. if (!minVector || !maxVector) {
  30283. return {
  30284. min: BABYLON.Vector3.Zero(),
  30285. max: BABYLON.Vector3.Zero()
  30286. };
  30287. }
  30288. return {
  30289. min: minVector,
  30290. max: maxVector
  30291. };
  30292. };
  30293. /**
  30294. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30295. */
  30296. Mesh.Center = function (meshesOrMinMaxVector) {
  30297. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30298. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30299. };
  30300. /**
  30301. * Merge the array of meshes into a single mesh for performance reasons.
  30302. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30303. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30304. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30305. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30306. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30307. */
  30308. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30309. if (disposeSource === void 0) { disposeSource = true; }
  30310. var index;
  30311. if (!allow32BitsIndices) {
  30312. var totalVertices = 0;
  30313. // Counting vertices
  30314. for (index = 0; index < meshes.length; index++) {
  30315. if (meshes[index]) {
  30316. totalVertices += meshes[index].getTotalVertices();
  30317. if (totalVertices > 65536) {
  30318. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30319. return null;
  30320. }
  30321. }
  30322. }
  30323. }
  30324. // Merge
  30325. var vertexData = null;
  30326. var otherVertexData;
  30327. var indiceArray = new Array();
  30328. var source = null;
  30329. for (index = 0; index < meshes.length; index++) {
  30330. if (meshes[index]) {
  30331. meshes[index].computeWorldMatrix(true);
  30332. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30333. otherVertexData.transform(meshes[index].getWorldMatrix());
  30334. if (vertexData) {
  30335. vertexData.merge(otherVertexData);
  30336. }
  30337. else {
  30338. vertexData = otherVertexData;
  30339. source = meshes[index];
  30340. }
  30341. if (subdivideWithSubMeshes) {
  30342. indiceArray.push(meshes[index].getTotalIndices());
  30343. }
  30344. }
  30345. }
  30346. source = source;
  30347. if (!meshSubclass) {
  30348. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30349. }
  30350. vertexData.applyToMesh(meshSubclass);
  30351. // Setting properties
  30352. meshSubclass.material = source.material;
  30353. meshSubclass.checkCollisions = source.checkCollisions;
  30354. // Cleaning
  30355. if (disposeSource) {
  30356. for (index = 0; index < meshes.length; index++) {
  30357. if (meshes[index]) {
  30358. meshes[index].dispose();
  30359. }
  30360. }
  30361. }
  30362. // Subdivide
  30363. if (subdivideWithSubMeshes) {
  30364. //-- Suppresions du submesh global
  30365. meshSubclass.releaseSubMeshes();
  30366. index = 0;
  30367. var offset = 0;
  30368. //-- aplique la subdivision en fonction du tableau d'indices
  30369. while (index < indiceArray.length) {
  30370. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30371. offset += indiceArray[index];
  30372. index++;
  30373. }
  30374. }
  30375. return meshSubclass;
  30376. };
  30377. // Consts
  30378. Mesh._FRONTSIDE = 0;
  30379. Mesh._BACKSIDE = 1;
  30380. Mesh._DOUBLESIDE = 2;
  30381. Mesh._DEFAULTSIDE = 0;
  30382. Mesh._NO_CAP = 0;
  30383. Mesh._CAP_START = 1;
  30384. Mesh._CAP_END = 2;
  30385. Mesh._CAP_ALL = 3;
  30386. return Mesh;
  30387. }(BABYLON.AbstractMesh));
  30388. BABYLON.Mesh = Mesh;
  30389. })(BABYLON || (BABYLON = {}));
  30390. //# sourceMappingURL=babylon.mesh.js.map
  30391. var BABYLON;
  30392. (function (BABYLON) {
  30393. var BaseSubMesh = /** @class */ (function () {
  30394. function BaseSubMesh() {
  30395. }
  30396. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30397. get: function () {
  30398. return this._materialEffect;
  30399. },
  30400. enumerable: true,
  30401. configurable: true
  30402. });
  30403. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30404. if (defines === void 0) { defines = null; }
  30405. if (this._materialEffect === effect) {
  30406. if (!effect) {
  30407. this._materialDefines = null;
  30408. }
  30409. return;
  30410. }
  30411. this._materialDefines = defines;
  30412. this._materialEffect = effect;
  30413. };
  30414. return BaseSubMesh;
  30415. }());
  30416. BABYLON.BaseSubMesh = BaseSubMesh;
  30417. var SubMesh = /** @class */ (function (_super) {
  30418. __extends(SubMesh, _super);
  30419. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30420. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30421. var _this = _super.call(this) || this;
  30422. _this.materialIndex = materialIndex;
  30423. _this.verticesStart = verticesStart;
  30424. _this.verticesCount = verticesCount;
  30425. _this.indexStart = indexStart;
  30426. _this.indexCount = indexCount;
  30427. _this._renderId = 0;
  30428. _this._mesh = mesh;
  30429. _this._renderingMesh = renderingMesh || mesh;
  30430. mesh.subMeshes.push(_this);
  30431. _this._trianglePlanes = [];
  30432. _this._id = mesh.subMeshes.length - 1;
  30433. if (createBoundingBox) {
  30434. _this.refreshBoundingInfo();
  30435. mesh.computeWorldMatrix(true);
  30436. }
  30437. return _this;
  30438. }
  30439. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30440. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30441. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30442. };
  30443. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30444. get: function () {
  30445. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30446. },
  30447. enumerable: true,
  30448. configurable: true
  30449. });
  30450. /**
  30451. * Returns the submesh BoudingInfo object.
  30452. */
  30453. SubMesh.prototype.getBoundingInfo = function () {
  30454. if (this.IsGlobal) {
  30455. return this._mesh.getBoundingInfo();
  30456. }
  30457. return this._boundingInfo;
  30458. };
  30459. /**
  30460. * Sets the submesh BoundingInfo.
  30461. * Return the SubMesh.
  30462. */
  30463. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30464. this._boundingInfo = boundingInfo;
  30465. return this;
  30466. };
  30467. /**
  30468. * Returns the mesh of the current submesh.
  30469. */
  30470. SubMesh.prototype.getMesh = function () {
  30471. return this._mesh;
  30472. };
  30473. /**
  30474. * Returns the rendering mesh of the submesh.
  30475. */
  30476. SubMesh.prototype.getRenderingMesh = function () {
  30477. return this._renderingMesh;
  30478. };
  30479. /**
  30480. * Returns the submesh material.
  30481. */
  30482. SubMesh.prototype.getMaterial = function () {
  30483. var rootMaterial = this._renderingMesh.material;
  30484. if (rootMaterial === null || rootMaterial === undefined) {
  30485. return this._mesh.getScene().defaultMaterial;
  30486. }
  30487. else if (rootMaterial.getSubMaterial) {
  30488. var multiMaterial = rootMaterial;
  30489. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30490. if (this._currentMaterial !== effectiveMaterial) {
  30491. this._currentMaterial = effectiveMaterial;
  30492. this._materialDefines = null;
  30493. }
  30494. return effectiveMaterial;
  30495. }
  30496. return rootMaterial;
  30497. };
  30498. // Methods
  30499. /**
  30500. * Sets a new updated BoundingInfo object to the submesh.
  30501. * Returns the SubMesh.
  30502. */
  30503. SubMesh.prototype.refreshBoundingInfo = function () {
  30504. this._lastColliderWorldVertices = null;
  30505. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30506. return this;
  30507. }
  30508. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30509. if (!data) {
  30510. this._boundingInfo = this._mesh.getBoundingInfo();
  30511. return this;
  30512. }
  30513. var indices = this._renderingMesh.getIndices();
  30514. var extend;
  30515. //is this the only submesh?
  30516. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30517. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30518. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30519. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30520. }
  30521. else {
  30522. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30523. }
  30524. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30525. return this;
  30526. };
  30527. SubMesh.prototype._checkCollision = function (collider) {
  30528. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30529. return boundingInfo._checkCollision(collider);
  30530. };
  30531. /**
  30532. * Updates the submesh BoundingInfo.
  30533. * Returns the Submesh.
  30534. */
  30535. SubMesh.prototype.updateBoundingInfo = function (world) {
  30536. var boundingInfo = this.getBoundingInfo();
  30537. if (!boundingInfo) {
  30538. this.refreshBoundingInfo();
  30539. boundingInfo = this.getBoundingInfo();
  30540. }
  30541. boundingInfo.update(world);
  30542. return this;
  30543. };
  30544. /**
  30545. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30546. * Boolean returned.
  30547. */
  30548. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30549. var boundingInfo = this.getBoundingInfo();
  30550. if (!boundingInfo) {
  30551. return false;
  30552. }
  30553. return boundingInfo.isInFrustum(frustumPlanes);
  30554. };
  30555. /**
  30556. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30557. * Boolean returned.
  30558. */
  30559. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30560. var boundingInfo = this.getBoundingInfo();
  30561. if (!boundingInfo) {
  30562. return false;
  30563. }
  30564. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30565. };
  30566. /**
  30567. * Renders the submesh.
  30568. * Returns it.
  30569. */
  30570. SubMesh.prototype.render = function (enableAlphaMode) {
  30571. this._renderingMesh.render(this, enableAlphaMode);
  30572. return this;
  30573. };
  30574. /**
  30575. * Returns a new Index Buffer.
  30576. * Type returned : WebGLBuffer.
  30577. */
  30578. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30579. if (!this._linesIndexBuffer) {
  30580. var linesIndices = [];
  30581. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30582. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30583. }
  30584. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30585. this.linesIndexCount = linesIndices.length;
  30586. }
  30587. return this._linesIndexBuffer;
  30588. };
  30589. /**
  30590. * True is the passed Ray intersects the submesh bounding box.
  30591. * Boolean returned.
  30592. */
  30593. SubMesh.prototype.canIntersects = function (ray) {
  30594. var boundingInfo = this.getBoundingInfo();
  30595. if (!boundingInfo) {
  30596. return false;
  30597. }
  30598. return ray.intersectsBox(boundingInfo.boundingBox);
  30599. };
  30600. /**
  30601. * Returns an object IntersectionInfo.
  30602. */
  30603. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30604. var intersectInfo = null;
  30605. // LineMesh first as it's also a Mesh...
  30606. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30607. var lineMesh = this._mesh;
  30608. // Line test
  30609. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30610. var p0 = positions[indices[index]];
  30611. var p1 = positions[indices[index + 1]];
  30612. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30613. if (length < 0) {
  30614. continue;
  30615. }
  30616. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30617. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30618. if (fastCheck) {
  30619. break;
  30620. }
  30621. }
  30622. }
  30623. }
  30624. else {
  30625. // Triangles test
  30626. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30627. var p0 = positions[indices[index]];
  30628. var p1 = positions[indices[index + 1]];
  30629. var p2 = positions[indices[index + 2]];
  30630. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30631. if (currentIntersectInfo) {
  30632. if (currentIntersectInfo.distance < 0) {
  30633. continue;
  30634. }
  30635. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30636. intersectInfo = currentIntersectInfo;
  30637. intersectInfo.faceId = index / 3;
  30638. if (fastCheck) {
  30639. break;
  30640. }
  30641. }
  30642. }
  30643. }
  30644. }
  30645. return intersectInfo;
  30646. };
  30647. SubMesh.prototype._rebuild = function () {
  30648. if (this._linesIndexBuffer) {
  30649. this._linesIndexBuffer = null;
  30650. }
  30651. };
  30652. // Clone
  30653. /**
  30654. * Creates a new Submesh from the passed Mesh.
  30655. */
  30656. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30657. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30658. if (!this.IsGlobal) {
  30659. var boundingInfo = this.getBoundingInfo();
  30660. if (!boundingInfo) {
  30661. return result;
  30662. }
  30663. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30664. }
  30665. return result;
  30666. };
  30667. // Dispose
  30668. /**
  30669. * Disposes the Submesh.
  30670. * Returns nothing.
  30671. */
  30672. SubMesh.prototype.dispose = function () {
  30673. if (this._linesIndexBuffer) {
  30674. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30675. this._linesIndexBuffer = null;
  30676. }
  30677. // Remove from mesh
  30678. var index = this._mesh.subMeshes.indexOf(this);
  30679. this._mesh.subMeshes.splice(index, 1);
  30680. };
  30681. // Statics
  30682. /**
  30683. * Creates a new Submesh from the passed parameters :
  30684. * - materialIndex (integer) : the index of the main mesh material.
  30685. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30686. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30687. * - mesh (Mesh) : the main mesh to create the submesh from.
  30688. * - renderingMesh (optional Mesh) : rendering mesh.
  30689. */
  30690. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30691. var minVertexIndex = Number.MAX_VALUE;
  30692. var maxVertexIndex = -Number.MAX_VALUE;
  30693. renderingMesh = (renderingMesh || mesh);
  30694. var indices = renderingMesh.getIndices();
  30695. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30696. var vertexIndex = indices[index];
  30697. if (vertexIndex < minVertexIndex)
  30698. minVertexIndex = vertexIndex;
  30699. if (vertexIndex > maxVertexIndex)
  30700. maxVertexIndex = vertexIndex;
  30701. }
  30702. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30703. };
  30704. return SubMesh;
  30705. }(BaseSubMesh));
  30706. BABYLON.SubMesh = SubMesh;
  30707. })(BABYLON || (BABYLON = {}));
  30708. //# sourceMappingURL=babylon.subMesh.js.map
  30709. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30710. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30711. s = arguments[i];
  30712. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30713. t[p] = s[p];
  30714. }
  30715. return t;
  30716. };
  30717. var BABYLON;
  30718. (function (BABYLON) {
  30719. /**
  30720. * Manages the defines for the Material.
  30721. */
  30722. var MaterialDefines = /** @class */ (function () {
  30723. function MaterialDefines() {
  30724. this._isDirty = true;
  30725. this._areLightsDirty = true;
  30726. this._areAttributesDirty = true;
  30727. this._areTexturesDirty = true;
  30728. this._areFresnelDirty = true;
  30729. this._areMiscDirty = true;
  30730. this._areImageProcessingDirty = true;
  30731. this._normals = false;
  30732. this._uvs = false;
  30733. this._needNormals = false;
  30734. this._needUVs = false;
  30735. }
  30736. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30737. /**
  30738. * Specifies if the material needs to be re-calculated.
  30739. */
  30740. get: function () {
  30741. return this._isDirty;
  30742. },
  30743. enumerable: true,
  30744. configurable: true
  30745. });
  30746. /**
  30747. * Marks the material to indicate that it has been re-calculated.
  30748. */
  30749. MaterialDefines.prototype.markAsProcessed = function () {
  30750. this._isDirty = false;
  30751. this._areAttributesDirty = false;
  30752. this._areTexturesDirty = false;
  30753. this._areFresnelDirty = false;
  30754. this._areLightsDirty = false;
  30755. this._areMiscDirty = false;
  30756. this._areImageProcessingDirty = false;
  30757. };
  30758. /**
  30759. * Marks the material to indicate that it needs to be re-calculated.
  30760. */
  30761. MaterialDefines.prototype.markAsUnprocessed = function () {
  30762. this._isDirty = true;
  30763. };
  30764. /**
  30765. * Marks the material to indicate all of its defines need to be re-calculated.
  30766. */
  30767. MaterialDefines.prototype.markAllAsDirty = function () {
  30768. this._areTexturesDirty = true;
  30769. this._areAttributesDirty = true;
  30770. this._areLightsDirty = true;
  30771. this._areFresnelDirty = true;
  30772. this._areMiscDirty = true;
  30773. this._areImageProcessingDirty = true;
  30774. this._isDirty = true;
  30775. };
  30776. /**
  30777. * Marks the material to indicate that image processing needs to be re-calculated.
  30778. */
  30779. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30780. this._areImageProcessingDirty = true;
  30781. this._isDirty = true;
  30782. };
  30783. /**
  30784. * Marks the material to indicate the lights need to be re-calculated.
  30785. */
  30786. MaterialDefines.prototype.markAsLightDirty = function () {
  30787. this._areLightsDirty = true;
  30788. this._isDirty = true;
  30789. };
  30790. /**
  30791. * Marks the attribute state as changed.
  30792. */
  30793. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30794. this._areAttributesDirty = true;
  30795. this._isDirty = true;
  30796. };
  30797. /**
  30798. * Marks the texture state as changed.
  30799. */
  30800. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30801. this._areTexturesDirty = true;
  30802. this._isDirty = true;
  30803. };
  30804. /**
  30805. * Marks the fresnel state as changed.
  30806. */
  30807. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30808. this._areFresnelDirty = true;
  30809. this._isDirty = true;
  30810. };
  30811. /**
  30812. * Marks the misc state as changed.
  30813. */
  30814. MaterialDefines.prototype.markAsMiscDirty = function () {
  30815. this._areMiscDirty = true;
  30816. this._isDirty = true;
  30817. };
  30818. /**
  30819. * Rebuilds the material defines.
  30820. */
  30821. MaterialDefines.prototype.rebuild = function () {
  30822. if (this._keys) {
  30823. delete this._keys;
  30824. }
  30825. this._keys = [];
  30826. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30827. var key = _a[_i];
  30828. if (key[0] === "_") {
  30829. continue;
  30830. }
  30831. this._keys.push(key);
  30832. }
  30833. };
  30834. /**
  30835. * Specifies if two material defines are equal.
  30836. * @param other - A material define instance to compare to.
  30837. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30838. */
  30839. MaterialDefines.prototype.isEqual = function (other) {
  30840. if (this._keys.length !== other._keys.length) {
  30841. return false;
  30842. }
  30843. for (var index = 0; index < this._keys.length; index++) {
  30844. var prop = this._keys[index];
  30845. if (this[prop] !== other[prop]) {
  30846. return false;
  30847. }
  30848. }
  30849. return true;
  30850. };
  30851. /**
  30852. * Clones this instance's defines to another instance.
  30853. * @param other - material defines to clone values to.
  30854. */
  30855. MaterialDefines.prototype.cloneTo = function (other) {
  30856. if (this._keys.length !== other._keys.length) {
  30857. other._keys = this._keys.slice(0);
  30858. }
  30859. for (var index = 0; index < this._keys.length; index++) {
  30860. var prop = this._keys[index];
  30861. other[prop] = this[prop];
  30862. }
  30863. };
  30864. /**
  30865. * Resets the material define values.
  30866. */
  30867. MaterialDefines.prototype.reset = function () {
  30868. for (var index = 0; index < this._keys.length; index++) {
  30869. var prop = this._keys[index];
  30870. if (typeof (this[prop]) === "number") {
  30871. this[prop] = 0;
  30872. }
  30873. else {
  30874. this[prop] = false;
  30875. }
  30876. }
  30877. };
  30878. /**
  30879. * Converts the material define values to a string.
  30880. * @returns - String of material define information.
  30881. */
  30882. MaterialDefines.prototype.toString = function () {
  30883. var result = "";
  30884. for (var index = 0; index < this._keys.length; index++) {
  30885. var prop = this._keys[index];
  30886. var value = this[prop];
  30887. if (typeof (value) === "number") {
  30888. result += "#define " + prop + " " + this[prop] + "\n";
  30889. }
  30890. else if (value) {
  30891. result += "#define " + prop + "\n";
  30892. }
  30893. }
  30894. return result;
  30895. };
  30896. return MaterialDefines;
  30897. }());
  30898. BABYLON.MaterialDefines = MaterialDefines;
  30899. /**
  30900. * This offers the main features of a material in BJS.
  30901. */
  30902. var Material = /** @class */ (function () {
  30903. /**
  30904. * Creates a material instance.
  30905. * @param name - The name of the material.
  30906. * @param scene - The BJS scene to reference.
  30907. * @param doNotAdd - Specifies if the material should be added to the scene.
  30908. */
  30909. function Material(name, scene, doNotAdd) {
  30910. /**
  30911. * Specifies if the ready state should be checked on each call.
  30912. */
  30913. this.checkReadyOnEveryCall = false;
  30914. /**
  30915. * Specifies if the ready state should be checked once.
  30916. */
  30917. this.checkReadyOnlyOnce = false;
  30918. /**
  30919. * The state of the material.
  30920. */
  30921. this.state = "";
  30922. /**
  30923. * The alpha value of the material.
  30924. */
  30925. this._alpha = 1.0;
  30926. /**
  30927. * Specifies if back face culling is enabled.
  30928. */
  30929. this._backFaceCulling = true;
  30930. /**
  30931. * Specifies if the material should be serialized.
  30932. */
  30933. this.doNotSerialize = false;
  30934. /**
  30935. * Specifies if the effect should be stored on sub meshes.
  30936. */
  30937. this.storeEffectOnSubMeshes = false;
  30938. /**
  30939. * An event triggered when the material is disposed.
  30940. * @type {BABYLON.Observable}
  30941. */
  30942. this.onDisposeObservable = new BABYLON.Observable();
  30943. /**
  30944. * An event triggered when the material is bound.
  30945. * @type {BABYLON.Observable}
  30946. */
  30947. this.onBindObservable = new BABYLON.Observable();
  30948. /**
  30949. * An event triggered when the material is unbound.
  30950. * @type {BABYLON.Observable}
  30951. */
  30952. this.onUnBindObservable = new BABYLON.Observable();
  30953. /**
  30954. * Stores the value of the alpha mode.
  30955. */
  30956. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30957. /**
  30958. * Stores the state of the need depth pre-pass value.
  30959. */
  30960. this._needDepthPrePass = false;
  30961. /**
  30962. * Specifies if depth writing should be disabled.
  30963. */
  30964. this.disableDepthWrite = false;
  30965. /**
  30966. * Specifies if depth writing should be forced.
  30967. */
  30968. this.forceDepthWrite = false;
  30969. /**
  30970. * Specifies if there should be a separate pass for culling.
  30971. */
  30972. this.separateCullingPass = false;
  30973. /**
  30974. * Stores the state specifing if fog should be enabled.
  30975. */
  30976. this._fogEnabled = true;
  30977. /**
  30978. * Stores the size of points.
  30979. */
  30980. this.pointSize = 1.0;
  30981. /**
  30982. * Stores the z offset value.
  30983. */
  30984. this.zOffset = 0;
  30985. /**
  30986. * Specifies if the material was previously ready.
  30987. */
  30988. this._wasPreviouslyReady = false;
  30989. /**
  30990. * Stores the fill mode state.
  30991. */
  30992. this._fillMode = Material.TriangleFillMode;
  30993. this.name = name;
  30994. this.id = name || BABYLON.Tools.RandomId();
  30995. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30996. if (this._scene.useRightHandedSystem) {
  30997. this.sideOrientation = Material.ClockWiseSideOrientation;
  30998. }
  30999. else {
  31000. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31001. }
  31002. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31003. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31004. if (!doNotAdd) {
  31005. this._scene.materials.push(this);
  31006. }
  31007. }
  31008. Object.defineProperty(Material, "TriangleFillMode", {
  31009. /**
  31010. * Returns the triangle fill mode.
  31011. */
  31012. get: function () {
  31013. return Material._TriangleFillMode;
  31014. },
  31015. enumerable: true,
  31016. configurable: true
  31017. });
  31018. Object.defineProperty(Material, "WireFrameFillMode", {
  31019. /**
  31020. * Returns the wireframe mode.
  31021. */
  31022. get: function () {
  31023. return Material._WireFrameFillMode;
  31024. },
  31025. enumerable: true,
  31026. configurable: true
  31027. });
  31028. Object.defineProperty(Material, "PointFillMode", {
  31029. /**
  31030. * Returns the point fill mode.
  31031. */
  31032. get: function () {
  31033. return Material._PointFillMode;
  31034. },
  31035. enumerable: true,
  31036. configurable: true
  31037. });
  31038. Object.defineProperty(Material, "PointListDrawMode", {
  31039. /**
  31040. * Returns the point list draw mode.
  31041. */
  31042. get: function () {
  31043. return Material._PointListDrawMode;
  31044. },
  31045. enumerable: true,
  31046. configurable: true
  31047. });
  31048. Object.defineProperty(Material, "LineListDrawMode", {
  31049. /**
  31050. * Returns the line list draw mode.
  31051. */
  31052. get: function () {
  31053. return Material._LineListDrawMode;
  31054. },
  31055. enumerable: true,
  31056. configurable: true
  31057. });
  31058. Object.defineProperty(Material, "LineLoopDrawMode", {
  31059. /**
  31060. * Returns the line loop draw mode.
  31061. */
  31062. get: function () {
  31063. return Material._LineLoopDrawMode;
  31064. },
  31065. enumerable: true,
  31066. configurable: true
  31067. });
  31068. Object.defineProperty(Material, "LineStripDrawMode", {
  31069. /**
  31070. * Returns the line strip draw mode.
  31071. */
  31072. get: function () {
  31073. return Material._LineStripDrawMode;
  31074. },
  31075. enumerable: true,
  31076. configurable: true
  31077. });
  31078. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31079. /**
  31080. * Returns the triangle strip draw mode.
  31081. */
  31082. get: function () {
  31083. return Material._TriangleStripDrawMode;
  31084. },
  31085. enumerable: true,
  31086. configurable: true
  31087. });
  31088. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31089. /**
  31090. * Returns the triangle fan draw mode.
  31091. */
  31092. get: function () {
  31093. return Material._TriangleFanDrawMode;
  31094. },
  31095. enumerable: true,
  31096. configurable: true
  31097. });
  31098. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31099. /**
  31100. * Returns the clock-wise side orientation.
  31101. */
  31102. get: function () {
  31103. return Material._ClockWiseSideOrientation;
  31104. },
  31105. enumerable: true,
  31106. configurable: true
  31107. });
  31108. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31109. /**
  31110. * Returns the counter clock-wise side orientation.
  31111. */
  31112. get: function () {
  31113. return Material._CounterClockWiseSideOrientation;
  31114. },
  31115. enumerable: true,
  31116. configurable: true
  31117. });
  31118. Object.defineProperty(Material, "TextureDirtyFlag", {
  31119. /**
  31120. * Returns the dirty texture flag value.
  31121. */
  31122. get: function () {
  31123. return Material._TextureDirtyFlag;
  31124. },
  31125. enumerable: true,
  31126. configurable: true
  31127. });
  31128. Object.defineProperty(Material, "LightDirtyFlag", {
  31129. /**
  31130. * Returns the dirty light flag value.
  31131. */
  31132. get: function () {
  31133. return Material._LightDirtyFlag;
  31134. },
  31135. enumerable: true,
  31136. configurable: true
  31137. });
  31138. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31139. /**
  31140. * Returns the dirty fresnel flag value.
  31141. */
  31142. get: function () {
  31143. return Material._FresnelDirtyFlag;
  31144. },
  31145. enumerable: true,
  31146. configurable: true
  31147. });
  31148. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31149. /**
  31150. * Returns the dirty attributes flag value.
  31151. */
  31152. get: function () {
  31153. return Material._AttributesDirtyFlag;
  31154. },
  31155. enumerable: true,
  31156. configurable: true
  31157. });
  31158. Object.defineProperty(Material, "MiscDirtyFlag", {
  31159. /**
  31160. * Returns the dirty misc flag value.
  31161. */
  31162. get: function () {
  31163. return Material._MiscDirtyFlag;
  31164. },
  31165. enumerable: true,
  31166. configurable: true
  31167. });
  31168. Object.defineProperty(Material.prototype, "alpha", {
  31169. /**
  31170. * Gets the alpha value of the material.
  31171. */
  31172. get: function () {
  31173. return this._alpha;
  31174. },
  31175. /**
  31176. * Sets the alpha value of the material.
  31177. */
  31178. set: function (value) {
  31179. if (this._alpha === value) {
  31180. return;
  31181. }
  31182. this._alpha = value;
  31183. this.markAsDirty(Material.MiscDirtyFlag);
  31184. },
  31185. enumerable: true,
  31186. configurable: true
  31187. });
  31188. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31189. /**
  31190. * Gets the back-face culling state.
  31191. */
  31192. get: function () {
  31193. return this._backFaceCulling;
  31194. },
  31195. /**
  31196. * Sets the back-face culling state.
  31197. */
  31198. set: function (value) {
  31199. if (this._backFaceCulling === value) {
  31200. return;
  31201. }
  31202. this._backFaceCulling = value;
  31203. this.markAsDirty(Material.TextureDirtyFlag);
  31204. },
  31205. enumerable: true,
  31206. configurable: true
  31207. });
  31208. Object.defineProperty(Material.prototype, "onDispose", {
  31209. /**
  31210. * Called during a dispose event.
  31211. */
  31212. set: function (callback) {
  31213. if (this._onDisposeObserver) {
  31214. this.onDisposeObservable.remove(this._onDisposeObserver);
  31215. }
  31216. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31217. },
  31218. enumerable: true,
  31219. configurable: true
  31220. });
  31221. Object.defineProperty(Material.prototype, "onBind", {
  31222. /**
  31223. * Called during a bind event.
  31224. */
  31225. set: function (callback) {
  31226. if (this._onBindObserver) {
  31227. this.onBindObservable.remove(this._onBindObserver);
  31228. }
  31229. this._onBindObserver = this.onBindObservable.add(callback);
  31230. },
  31231. enumerable: true,
  31232. configurable: true
  31233. });
  31234. Object.defineProperty(Material.prototype, "alphaMode", {
  31235. /**
  31236. * Gets the value of the alpha mode.
  31237. */
  31238. get: function () {
  31239. return this._alphaMode;
  31240. },
  31241. /**
  31242. * Sets the value of the alpha mode.
  31243. */
  31244. set: function (value) {
  31245. if (this._alphaMode === value) {
  31246. return;
  31247. }
  31248. this._alphaMode = value;
  31249. this.markAsDirty(Material.TextureDirtyFlag);
  31250. },
  31251. enumerable: true,
  31252. configurable: true
  31253. });
  31254. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31255. /**
  31256. * Gets the depth pre-pass value.
  31257. */
  31258. get: function () {
  31259. return this._needDepthPrePass;
  31260. },
  31261. /**
  31262. * Sets the need depth pre-pass value.
  31263. */
  31264. set: function (value) {
  31265. if (this._needDepthPrePass === value) {
  31266. return;
  31267. }
  31268. this._needDepthPrePass = value;
  31269. if (this._needDepthPrePass) {
  31270. this.checkReadyOnEveryCall = true;
  31271. }
  31272. },
  31273. enumerable: true,
  31274. configurable: true
  31275. });
  31276. Object.defineProperty(Material.prototype, "fogEnabled", {
  31277. /**
  31278. * Gets the value of the fog enabled state.
  31279. */
  31280. get: function () {
  31281. return this._fogEnabled;
  31282. },
  31283. /**
  31284. * Sets the state for enabling fog.
  31285. */
  31286. set: function (value) {
  31287. if (this._fogEnabled === value) {
  31288. return;
  31289. }
  31290. this._fogEnabled = value;
  31291. this.markAsDirty(Material.MiscDirtyFlag);
  31292. },
  31293. enumerable: true,
  31294. configurable: true
  31295. });
  31296. Object.defineProperty(Material.prototype, "wireframe", {
  31297. /**
  31298. * Gets a value specifying if wireframe mode is enabled.
  31299. */
  31300. get: function () {
  31301. return this._fillMode === Material.WireFrameFillMode;
  31302. },
  31303. /**
  31304. * Sets the state of wireframe mode.
  31305. */
  31306. set: function (value) {
  31307. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31308. },
  31309. enumerable: true,
  31310. configurable: true
  31311. });
  31312. Object.defineProperty(Material.prototype, "pointsCloud", {
  31313. /**
  31314. * Gets the value specifying if point clouds are enabled.
  31315. */
  31316. get: function () {
  31317. return this._fillMode === Material.PointFillMode;
  31318. },
  31319. /**
  31320. * Sets the state of point cloud mode.
  31321. */
  31322. set: function (value) {
  31323. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31324. },
  31325. enumerable: true,
  31326. configurable: true
  31327. });
  31328. Object.defineProperty(Material.prototype, "fillMode", {
  31329. /**
  31330. * Gets the material fill mode.
  31331. */
  31332. get: function () {
  31333. return this._fillMode;
  31334. },
  31335. /**
  31336. * Sets the material fill mode.
  31337. */
  31338. set: function (value) {
  31339. if (this._fillMode === value) {
  31340. return;
  31341. }
  31342. this._fillMode = value;
  31343. this.markAsDirty(Material.MiscDirtyFlag);
  31344. },
  31345. enumerable: true,
  31346. configurable: true
  31347. });
  31348. /**
  31349. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31350. * subclasses should override adding information pertainent to themselves.
  31351. * @returns - String with material information.
  31352. */
  31353. Material.prototype.toString = function (fullDetails) {
  31354. var ret = "Name: " + this.name;
  31355. if (fullDetails) {
  31356. }
  31357. return ret;
  31358. };
  31359. /**
  31360. * Gets the class name of the material.
  31361. * @returns - String with the class name of the material.
  31362. */
  31363. Material.prototype.getClassName = function () {
  31364. return "Material";
  31365. };
  31366. Object.defineProperty(Material.prototype, "isFrozen", {
  31367. /**
  31368. * Specifies if updates for the material been locked.
  31369. */
  31370. get: function () {
  31371. return this.checkReadyOnlyOnce;
  31372. },
  31373. enumerable: true,
  31374. configurable: true
  31375. });
  31376. /**
  31377. * Locks updates for the material.
  31378. */
  31379. Material.prototype.freeze = function () {
  31380. this.checkReadyOnlyOnce = true;
  31381. };
  31382. /**
  31383. * Unlocks updates for the material.
  31384. */
  31385. Material.prototype.unfreeze = function () {
  31386. this.checkReadyOnlyOnce = false;
  31387. };
  31388. /**
  31389. * Specifies if the material is ready to be used.
  31390. * @param mesh - BJS mesh.
  31391. * @param useInstances - Specifies if instances should be used.
  31392. * @returns - Boolean indicating if the material is ready to be used.
  31393. */
  31394. Material.prototype.isReady = function (mesh, useInstances) {
  31395. return true;
  31396. };
  31397. /**
  31398. * Specifies that the submesh is ready to be used.
  31399. * @param mesh - BJS mesh.
  31400. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31401. * @param useInstances - Specifies that instances should be used.
  31402. * @returns - boolean indicating that the submesh is ready or not.
  31403. */
  31404. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31405. return false;
  31406. };
  31407. /**
  31408. * Returns the material effect.
  31409. * @returns - Nullable material effect.
  31410. */
  31411. Material.prototype.getEffect = function () {
  31412. return this._effect;
  31413. };
  31414. /**
  31415. * Returns the BJS scene.
  31416. * @returns - BJS Scene.
  31417. */
  31418. Material.prototype.getScene = function () {
  31419. return this._scene;
  31420. };
  31421. /**
  31422. * Specifies if the material will require alpha blending
  31423. * @returns - Boolean specifying if alpha blending is needed.
  31424. */
  31425. Material.prototype.needAlphaBlending = function () {
  31426. return (this.alpha < 1.0);
  31427. };
  31428. /**
  31429. * Specifies if the mesh will require alpha blending.
  31430. * @param mesh - BJS mesh.
  31431. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31432. */
  31433. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31434. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31435. };
  31436. /**
  31437. * Specifies if this material should be rendered in alpha test mode.
  31438. * @returns - Boolean specifying if an alpha test is needed.
  31439. */
  31440. Material.prototype.needAlphaTesting = function () {
  31441. return false;
  31442. };
  31443. /**
  31444. * Gets the texture used for the alpha test.
  31445. * @returns - Nullable alpha test texture.
  31446. */
  31447. Material.prototype.getAlphaTestTexture = function () {
  31448. return null;
  31449. };
  31450. /**
  31451. * Marks the material to indicate that it needs to be re-calculated.
  31452. */
  31453. Material.prototype.markDirty = function () {
  31454. this._wasPreviouslyReady = false;
  31455. };
  31456. Material.prototype._preBind = function (effect, overrideOrientation) {
  31457. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31458. var engine = this._scene.getEngine();
  31459. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31460. var reverse = orientation === Material.ClockWiseSideOrientation;
  31461. engine.enableEffect(effect ? effect : this._effect);
  31462. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31463. return reverse;
  31464. };
  31465. /**
  31466. * Binds the material to the mesh.
  31467. * @param world - World transformation matrix.
  31468. * @param mesh - Mesh to bind the material to.
  31469. */
  31470. Material.prototype.bind = function (world, mesh) {
  31471. };
  31472. /**
  31473. * Binds the submesh to the material.
  31474. * @param world - World transformation matrix.
  31475. * @param mesh - Mesh containing the submesh.
  31476. * @param subMesh - Submesh to bind the material to.
  31477. */
  31478. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31479. };
  31480. /**
  31481. * Binds the world matrix to the material.
  31482. * @param world - World transformation matrix.
  31483. */
  31484. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31485. };
  31486. /**
  31487. * Binds the scene's uniform buffer to the effect.
  31488. * @param effect - Effect to bind to the scene uniform buffer.
  31489. * @param sceneUbo - Scene uniform buffer.
  31490. */
  31491. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31492. sceneUbo.bindToEffect(effect, "Scene");
  31493. };
  31494. /**
  31495. * Binds the view matrix to the effect.
  31496. * @param effect - Effect to bind the view matrix to.
  31497. */
  31498. Material.prototype.bindView = function (effect) {
  31499. if (!this._useUBO) {
  31500. effect.setMatrix("view", this.getScene().getViewMatrix());
  31501. }
  31502. else {
  31503. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31504. }
  31505. };
  31506. /**
  31507. * Binds the view projection matrix to the effect.
  31508. * @param effect - Effect to bind the view projection matrix to.
  31509. */
  31510. Material.prototype.bindViewProjection = function (effect) {
  31511. if (!this._useUBO) {
  31512. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31513. }
  31514. else {
  31515. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31516. }
  31517. };
  31518. /**
  31519. * Specifies if material alpha testing should be turned on for the mesh.
  31520. * @param mesh - BJS mesh.
  31521. */
  31522. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31523. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31524. };
  31525. /**
  31526. * Processes to execute after binding the material to a mesh.
  31527. * @param mesh - BJS mesh.
  31528. */
  31529. Material.prototype._afterBind = function (mesh) {
  31530. this._scene._cachedMaterial = this;
  31531. if (mesh) {
  31532. this._scene._cachedVisibility = mesh.visibility;
  31533. }
  31534. else {
  31535. this._scene._cachedVisibility = 1;
  31536. }
  31537. if (mesh) {
  31538. this.onBindObservable.notifyObservers(mesh);
  31539. }
  31540. if (this.disableDepthWrite) {
  31541. var engine = this._scene.getEngine();
  31542. this._cachedDepthWriteState = engine.getDepthWrite();
  31543. engine.setDepthWrite(false);
  31544. }
  31545. };
  31546. /**
  31547. * Unbinds the material from the mesh.
  31548. */
  31549. Material.prototype.unbind = function () {
  31550. this.onUnBindObservable.notifyObservers(this);
  31551. if (this.disableDepthWrite) {
  31552. var engine = this._scene.getEngine();
  31553. engine.setDepthWrite(this._cachedDepthWriteState);
  31554. }
  31555. };
  31556. /**
  31557. * Gets the active textures from the material.
  31558. * @returns - Array of textures.
  31559. */
  31560. Material.prototype.getActiveTextures = function () {
  31561. return [];
  31562. };
  31563. /**
  31564. * Specifies if the material uses a texture.
  31565. * @param texture - Texture to check against the material.
  31566. * @returns - Boolean specifying if the material uses the texture.
  31567. */
  31568. Material.prototype.hasTexture = function (texture) {
  31569. return false;
  31570. };
  31571. /**
  31572. * Makes a duplicate of the material, and gives it a new name.
  31573. * @param name - Name to call the duplicated material.
  31574. * @returns - Nullable cloned material
  31575. */
  31576. Material.prototype.clone = function (name) {
  31577. return null;
  31578. };
  31579. /**
  31580. * Gets the meshes bound to the material.
  31581. * @returns - Array of meshes bound to the material.
  31582. */
  31583. Material.prototype.getBindedMeshes = function () {
  31584. var result = new Array();
  31585. for (var index = 0; index < this._scene.meshes.length; index++) {
  31586. var mesh = this._scene.meshes[index];
  31587. if (mesh.material === this) {
  31588. result.push(mesh);
  31589. }
  31590. }
  31591. return result;
  31592. };
  31593. /**
  31594. * Force shader compilation
  31595. * @param mesh - BJS mesh.
  31596. * @param onCompiled - function to execute once the material is compiled.
  31597. * @param options - options to pass to this function.
  31598. */
  31599. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31600. var _this = this;
  31601. var localOptions = __assign({ clipPlane: false }, options);
  31602. var subMesh = new BABYLON.BaseSubMesh();
  31603. var scene = this.getScene();
  31604. var checkReady = function () {
  31605. if (!_this._scene || !_this._scene.getEngine()) {
  31606. return;
  31607. }
  31608. if (subMesh._materialDefines) {
  31609. subMesh._materialDefines._renderId = -1;
  31610. }
  31611. var clipPlaneState = scene.clipPlane;
  31612. if (localOptions.clipPlane) {
  31613. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31614. }
  31615. if (_this.storeEffectOnSubMeshes) {
  31616. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31617. if (onCompiled) {
  31618. onCompiled(_this);
  31619. }
  31620. }
  31621. else {
  31622. setTimeout(checkReady, 16);
  31623. }
  31624. }
  31625. else {
  31626. if (_this.isReady(mesh)) {
  31627. if (onCompiled) {
  31628. onCompiled(_this);
  31629. }
  31630. }
  31631. else {
  31632. setTimeout(checkReady, 16);
  31633. }
  31634. }
  31635. if (localOptions.clipPlane) {
  31636. scene.clipPlane = clipPlaneState;
  31637. }
  31638. };
  31639. checkReady();
  31640. };
  31641. /**
  31642. * Force shader compilation.
  31643. * @param mesh The mesh that will use this material
  31644. * @param options Additional options for compiling the shaders
  31645. * @returns A promise that resolves when the compilation completes
  31646. */
  31647. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31648. var _this = this;
  31649. return new Promise(function (resolve) {
  31650. _this.forceCompilation(mesh, function () {
  31651. resolve();
  31652. }, options);
  31653. });
  31654. };
  31655. /**
  31656. * Marks a define in the material to indicate that it needs to be re-computed.
  31657. * @param flag - Material define flag.
  31658. */
  31659. Material.prototype.markAsDirty = function (flag) {
  31660. if (flag & Material.TextureDirtyFlag) {
  31661. this._markAllSubMeshesAsTexturesDirty();
  31662. }
  31663. if (flag & Material.LightDirtyFlag) {
  31664. this._markAllSubMeshesAsLightsDirty();
  31665. }
  31666. if (flag & Material.FresnelDirtyFlag) {
  31667. this._markAllSubMeshesAsFresnelDirty();
  31668. }
  31669. if (flag & Material.AttributesDirtyFlag) {
  31670. this._markAllSubMeshesAsAttributesDirty();
  31671. }
  31672. if (flag & Material.MiscDirtyFlag) {
  31673. this._markAllSubMeshesAsMiscDirty();
  31674. }
  31675. this.getScene().resetCachedMaterial();
  31676. };
  31677. /**
  31678. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31679. * @param func - function which checks material defines against the submeshes.
  31680. */
  31681. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31682. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31683. var mesh = _a[_i];
  31684. if (!mesh.subMeshes) {
  31685. continue;
  31686. }
  31687. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31688. var subMesh = _c[_b];
  31689. if (subMesh.getMaterial() !== this) {
  31690. continue;
  31691. }
  31692. if (!subMesh._materialDefines) {
  31693. continue;
  31694. }
  31695. func(subMesh._materialDefines);
  31696. }
  31697. }
  31698. };
  31699. /**
  31700. * Indicates that image processing needs to be re-calculated for all submeshes.
  31701. */
  31702. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31703. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31704. };
  31705. /**
  31706. * Indicates that textures need to be re-calculated for all submeshes.
  31707. */
  31708. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31709. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31710. };
  31711. /**
  31712. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31713. */
  31714. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31715. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31716. };
  31717. /**
  31718. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31719. */
  31720. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31721. this._markAllSubMeshesAsDirty(function (defines) {
  31722. defines.markAsFresnelDirty();
  31723. defines.markAsMiscDirty();
  31724. });
  31725. };
  31726. /**
  31727. * Indicates that lights need to be re-calculated for all submeshes.
  31728. */
  31729. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31730. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31731. };
  31732. /**
  31733. * Indicates that attributes need to be re-calculated for all submeshes.
  31734. */
  31735. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31736. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31737. };
  31738. /**
  31739. * Indicates that misc needs to be re-calculated for all submeshes.
  31740. */
  31741. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31742. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31743. };
  31744. /**
  31745. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31746. */
  31747. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31748. this._markAllSubMeshesAsDirty(function (defines) {
  31749. defines.markAsTexturesDirty();
  31750. defines.markAsMiscDirty();
  31751. });
  31752. };
  31753. /**
  31754. * Disposes the material.
  31755. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31756. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31757. */
  31758. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31759. // Animations
  31760. this.getScene().stopAnimation(this);
  31761. this.getScene().freeProcessedMaterials();
  31762. // Remove from scene
  31763. var index = this._scene.materials.indexOf(this);
  31764. if (index >= 0) {
  31765. this._scene.materials.splice(index, 1);
  31766. }
  31767. // Remove from meshes
  31768. for (index = 0; index < this._scene.meshes.length; index++) {
  31769. var mesh = this._scene.meshes[index];
  31770. if (mesh.material === this) {
  31771. mesh.material = null;
  31772. if (mesh.geometry) {
  31773. var geometry = (mesh.geometry);
  31774. if (this.storeEffectOnSubMeshes) {
  31775. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31776. var subMesh = _a[_i];
  31777. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31778. if (forceDisposeEffect && subMesh._materialEffect) {
  31779. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31780. }
  31781. }
  31782. }
  31783. else {
  31784. geometry._releaseVertexArrayObject(this._effect);
  31785. }
  31786. }
  31787. }
  31788. }
  31789. this._uniformBuffer.dispose();
  31790. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31791. if (forceDisposeEffect && this._effect) {
  31792. if (!this.storeEffectOnSubMeshes) {
  31793. this._scene.getEngine()._releaseEffect(this._effect);
  31794. }
  31795. this._effect = null;
  31796. }
  31797. // Callback
  31798. this.onDisposeObservable.notifyObservers(this);
  31799. this.onDisposeObservable.clear();
  31800. this.onBindObservable.clear();
  31801. this.onUnBindObservable.clear();
  31802. };
  31803. /**
  31804. * Serializes this material.
  31805. * @returns - serialized material object.
  31806. */
  31807. Material.prototype.serialize = function () {
  31808. return BABYLON.SerializationHelper.Serialize(this);
  31809. };
  31810. /**
  31811. * Creates a MultiMaterial from parse MultiMaterial data.
  31812. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31813. * @param scene - BJS scene.
  31814. * @returns - MultiMaterial.
  31815. */
  31816. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31817. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31818. multiMaterial.id = parsedMultiMaterial.id;
  31819. if (BABYLON.Tags) {
  31820. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31821. }
  31822. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31823. var subMatId = parsedMultiMaterial.materials[matIndex];
  31824. if (subMatId) {
  31825. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31826. }
  31827. else {
  31828. multiMaterial.subMaterials.push(null);
  31829. }
  31830. }
  31831. return multiMaterial;
  31832. };
  31833. /**
  31834. * Creates a material from parsed material data.
  31835. * @param parsedMaterial - Parsed material data.
  31836. * @param scene - BJS scene.
  31837. * @param rootUrl - Root URL containing the material information.
  31838. * @returns - Parsed material.
  31839. */
  31840. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31841. if (!parsedMaterial.customType) {
  31842. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31843. }
  31844. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31845. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31846. if (!BABYLON.LegacyPBRMaterial) {
  31847. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31848. return;
  31849. }
  31850. }
  31851. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31852. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31853. ;
  31854. };
  31855. // Triangle views
  31856. Material._TriangleFillMode = 0;
  31857. Material._WireFrameFillMode = 1;
  31858. Material._PointFillMode = 2;
  31859. // Draw modes
  31860. Material._PointListDrawMode = 3;
  31861. Material._LineListDrawMode = 4;
  31862. Material._LineLoopDrawMode = 5;
  31863. Material._LineStripDrawMode = 6;
  31864. Material._TriangleStripDrawMode = 7;
  31865. Material._TriangleFanDrawMode = 8;
  31866. /**
  31867. * Stores the clock-wise side orientation.
  31868. */
  31869. Material._ClockWiseSideOrientation = 0;
  31870. /**
  31871. * Stores the counter clock-wise side orientation.
  31872. */
  31873. Material._CounterClockWiseSideOrientation = 1;
  31874. /**
  31875. * The dirty texture flag value.
  31876. */
  31877. Material._TextureDirtyFlag = 1;
  31878. /**
  31879. * The dirty light flag value.
  31880. */
  31881. Material._LightDirtyFlag = 2;
  31882. /**
  31883. * The dirty fresnel flag value.
  31884. */
  31885. Material._FresnelDirtyFlag = 4;
  31886. /**
  31887. * The dirty attribute flag value.
  31888. */
  31889. Material._AttributesDirtyFlag = 8;
  31890. /**
  31891. * The dirty misc flag value.
  31892. */
  31893. Material._MiscDirtyFlag = 16;
  31894. __decorate([
  31895. BABYLON.serialize()
  31896. ], Material.prototype, "id", void 0);
  31897. __decorate([
  31898. BABYLON.serialize()
  31899. ], Material.prototype, "name", void 0);
  31900. __decorate([
  31901. BABYLON.serialize()
  31902. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31903. __decorate([
  31904. BABYLON.serialize()
  31905. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31906. __decorate([
  31907. BABYLON.serialize()
  31908. ], Material.prototype, "state", void 0);
  31909. __decorate([
  31910. BABYLON.serialize("alpha")
  31911. ], Material.prototype, "_alpha", void 0);
  31912. __decorate([
  31913. BABYLON.serialize("backFaceCulling")
  31914. ], Material.prototype, "_backFaceCulling", void 0);
  31915. __decorate([
  31916. BABYLON.serialize()
  31917. ], Material.prototype, "sideOrientation", void 0);
  31918. __decorate([
  31919. BABYLON.serialize("alphaMode")
  31920. ], Material.prototype, "_alphaMode", void 0);
  31921. __decorate([
  31922. BABYLON.serialize()
  31923. ], Material.prototype, "_needDepthPrePass", void 0);
  31924. __decorate([
  31925. BABYLON.serialize()
  31926. ], Material.prototype, "disableDepthWrite", void 0);
  31927. __decorate([
  31928. BABYLON.serialize()
  31929. ], Material.prototype, "forceDepthWrite", void 0);
  31930. __decorate([
  31931. BABYLON.serialize()
  31932. ], Material.prototype, "separateCullingPass", void 0);
  31933. __decorate([
  31934. BABYLON.serialize("fogEnabled")
  31935. ], Material.prototype, "_fogEnabled", void 0);
  31936. __decorate([
  31937. BABYLON.serialize()
  31938. ], Material.prototype, "pointSize", void 0);
  31939. __decorate([
  31940. BABYLON.serialize()
  31941. ], Material.prototype, "zOffset", void 0);
  31942. __decorate([
  31943. BABYLON.serialize()
  31944. ], Material.prototype, "wireframe", null);
  31945. __decorate([
  31946. BABYLON.serialize()
  31947. ], Material.prototype, "pointsCloud", null);
  31948. __decorate([
  31949. BABYLON.serialize()
  31950. ], Material.prototype, "fillMode", null);
  31951. return Material;
  31952. }());
  31953. BABYLON.Material = Material;
  31954. })(BABYLON || (BABYLON = {}));
  31955. //# sourceMappingURL=babylon.material.js.map
  31956. var BABYLON;
  31957. (function (BABYLON) {
  31958. var UniformBuffer = /** @class */ (function () {
  31959. /**
  31960. * Uniform buffer objects.
  31961. *
  31962. * Handles blocks of uniform on the GPU.
  31963. *
  31964. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31965. *
  31966. * For more information, please refer to :
  31967. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31968. */
  31969. function UniformBuffer(engine, data, dynamic) {
  31970. this._engine = engine;
  31971. this._noUBO = !engine.supportsUniformBuffers;
  31972. this._dynamic = dynamic;
  31973. this._data = data || [];
  31974. this._uniformLocations = {};
  31975. this._uniformSizes = {};
  31976. this._uniformLocationPointer = 0;
  31977. this._needSync = false;
  31978. if (this._noUBO) {
  31979. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31980. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31981. this.updateFloat = this._updateFloatForEffect;
  31982. this.updateFloat2 = this._updateFloat2ForEffect;
  31983. this.updateFloat3 = this._updateFloat3ForEffect;
  31984. this.updateFloat4 = this._updateFloat4ForEffect;
  31985. this.updateMatrix = this._updateMatrixForEffect;
  31986. this.updateVector3 = this._updateVector3ForEffect;
  31987. this.updateVector4 = this._updateVector4ForEffect;
  31988. this.updateColor3 = this._updateColor3ForEffect;
  31989. this.updateColor4 = this._updateColor4ForEffect;
  31990. }
  31991. else {
  31992. this._engine._uniformBuffers.push(this);
  31993. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31994. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31995. this.updateFloat = this._updateFloatForUniform;
  31996. this.updateFloat2 = this._updateFloat2ForUniform;
  31997. this.updateFloat3 = this._updateFloat3ForUniform;
  31998. this.updateFloat4 = this._updateFloat4ForUniform;
  31999. this.updateMatrix = this._updateMatrixForUniform;
  32000. this.updateVector3 = this._updateVector3ForUniform;
  32001. this.updateVector4 = this._updateVector4ForUniform;
  32002. this.updateColor3 = this._updateColor3ForUniform;
  32003. this.updateColor4 = this._updateColor4ForUniform;
  32004. }
  32005. }
  32006. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32007. // Properties
  32008. /**
  32009. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32010. * or just falling back on setUniformXXX calls.
  32011. */
  32012. get: function () {
  32013. return !this._noUBO;
  32014. },
  32015. enumerable: true,
  32016. configurable: true
  32017. });
  32018. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32019. /**
  32020. * Indicates if the WebGL underlying uniform buffer is in sync
  32021. * with the javascript cache data.
  32022. */
  32023. get: function () {
  32024. return !this._needSync;
  32025. },
  32026. enumerable: true,
  32027. configurable: true
  32028. });
  32029. /**
  32030. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32031. * Also, a dynamic UniformBuffer will disable cache verification and always
  32032. * update the underlying WebGL uniform buffer to the GPU.
  32033. */
  32034. UniformBuffer.prototype.isDynamic = function () {
  32035. return this._dynamic !== undefined;
  32036. };
  32037. /**
  32038. * The data cache on JS side.
  32039. */
  32040. UniformBuffer.prototype.getData = function () {
  32041. return this._bufferData;
  32042. };
  32043. /**
  32044. * The underlying WebGL Uniform buffer.
  32045. */
  32046. UniformBuffer.prototype.getBuffer = function () {
  32047. return this._buffer;
  32048. };
  32049. /**
  32050. * std140 layout specifies how to align data within an UBO structure.
  32051. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32052. * for specs.
  32053. */
  32054. UniformBuffer.prototype._fillAlignment = function (size) {
  32055. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32056. // and 4x4 matrices
  32057. // TODO : change if other types are used
  32058. var alignment;
  32059. if (size <= 2) {
  32060. alignment = size;
  32061. }
  32062. else {
  32063. alignment = 4;
  32064. }
  32065. if ((this._uniformLocationPointer % alignment) !== 0) {
  32066. var oldPointer = this._uniformLocationPointer;
  32067. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32068. var diff = this._uniformLocationPointer - oldPointer;
  32069. for (var i = 0; i < diff; i++) {
  32070. this._data.push(0);
  32071. }
  32072. }
  32073. };
  32074. /**
  32075. * Adds an uniform in the buffer.
  32076. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32077. * for the layout to be correct !
  32078. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32079. * @param {number|number[]} size Data size, or data directly.
  32080. */
  32081. UniformBuffer.prototype.addUniform = function (name, size) {
  32082. if (this._noUBO) {
  32083. return;
  32084. }
  32085. if (this._uniformLocations[name] !== undefined) {
  32086. // Already existing uniform
  32087. return;
  32088. }
  32089. // This function must be called in the order of the shader layout !
  32090. // size can be the size of the uniform, or data directly
  32091. var data;
  32092. if (size instanceof Array) {
  32093. data = size;
  32094. size = data.length;
  32095. }
  32096. else {
  32097. size = size;
  32098. data = [];
  32099. // Fill with zeros
  32100. for (var i = 0; i < size; i++) {
  32101. data.push(0);
  32102. }
  32103. }
  32104. this._fillAlignment(size);
  32105. this._uniformSizes[name] = size;
  32106. this._uniformLocations[name] = this._uniformLocationPointer;
  32107. this._uniformLocationPointer += size;
  32108. for (var i = 0; i < size; i++) {
  32109. this._data.push(data[i]);
  32110. }
  32111. this._needSync = true;
  32112. };
  32113. /**
  32114. * Wrapper for addUniform.
  32115. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32116. * @param {Matrix} mat A 4x4 matrix.
  32117. */
  32118. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32119. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32120. };
  32121. /**
  32122. * Wrapper for addUniform.
  32123. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32124. * @param {number} x
  32125. * @param {number} y
  32126. */
  32127. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32128. var temp = [x, y];
  32129. this.addUniform(name, temp);
  32130. };
  32131. /**
  32132. * Wrapper for addUniform.
  32133. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32134. * @param {number} x
  32135. * @param {number} y
  32136. * @param {number} z
  32137. */
  32138. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32139. var temp = [x, y, z];
  32140. this.addUniform(name, temp);
  32141. };
  32142. /**
  32143. * Wrapper for addUniform.
  32144. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32145. * @param {Color3} color
  32146. */
  32147. UniformBuffer.prototype.addColor3 = function (name, color) {
  32148. var temp = new Array();
  32149. color.toArray(temp);
  32150. this.addUniform(name, temp);
  32151. };
  32152. /**
  32153. * Wrapper for addUniform.
  32154. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32155. * @param {Color3} color
  32156. * @param {number} alpha
  32157. */
  32158. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32159. var temp = new Array();
  32160. color.toArray(temp);
  32161. temp.push(alpha);
  32162. this.addUniform(name, temp);
  32163. };
  32164. /**
  32165. * Wrapper for addUniform.
  32166. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32167. * @param {Vector3} vector
  32168. */
  32169. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32170. var temp = new Array();
  32171. vector.toArray(temp);
  32172. this.addUniform(name, temp);
  32173. };
  32174. /**
  32175. * Wrapper for addUniform.
  32176. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32177. */
  32178. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32179. this.addUniform(name, 12);
  32180. };
  32181. /**
  32182. * Wrapper for addUniform.
  32183. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32184. */
  32185. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32186. this.addUniform(name, 8);
  32187. };
  32188. /**
  32189. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32190. */
  32191. UniformBuffer.prototype.create = function () {
  32192. if (this._noUBO) {
  32193. return;
  32194. }
  32195. if (this._buffer) {
  32196. return; // nothing to do
  32197. }
  32198. // See spec, alignment must be filled as a vec4
  32199. this._fillAlignment(4);
  32200. this._bufferData = new Float32Array(this._data);
  32201. this._rebuild();
  32202. this._needSync = true;
  32203. };
  32204. UniformBuffer.prototype._rebuild = function () {
  32205. if (this._noUBO) {
  32206. return;
  32207. }
  32208. if (this._dynamic) {
  32209. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32210. }
  32211. else {
  32212. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32213. }
  32214. };
  32215. /**
  32216. * Updates the WebGL Uniform Buffer on the GPU.
  32217. * If the `dynamic` flag is set to true, no cache comparison is done.
  32218. * Otherwise, the buffer will be updated only if the cache differs.
  32219. */
  32220. UniformBuffer.prototype.update = function () {
  32221. if (!this._buffer) {
  32222. this.create();
  32223. return;
  32224. }
  32225. if (!this._dynamic && !this._needSync) {
  32226. return;
  32227. }
  32228. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32229. this._needSync = false;
  32230. };
  32231. /**
  32232. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32233. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32234. * @param {number[]|Float32Array} data Flattened data
  32235. * @param {number} size Size of the data.
  32236. */
  32237. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32238. var location = this._uniformLocations[uniformName];
  32239. if (location === undefined) {
  32240. if (this._buffer) {
  32241. // Cannot add an uniform if the buffer is already created
  32242. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32243. return;
  32244. }
  32245. this.addUniform(uniformName, size);
  32246. location = this._uniformLocations[uniformName];
  32247. }
  32248. if (!this._buffer) {
  32249. this.create();
  32250. }
  32251. if (!this._dynamic) {
  32252. // Cache for static uniform buffers
  32253. var changed = false;
  32254. for (var i = 0; i < size; i++) {
  32255. if (this._bufferData[location + i] !== data[i]) {
  32256. changed = true;
  32257. this._bufferData[location + i] = data[i];
  32258. }
  32259. }
  32260. this._needSync = this._needSync || changed;
  32261. }
  32262. else {
  32263. // No cache for dynamic
  32264. for (var i = 0; i < size; i++) {
  32265. this._bufferData[location + i] = data[i];
  32266. }
  32267. }
  32268. };
  32269. // Update methods
  32270. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32271. // To match std140, matrix must be realigned
  32272. for (var i = 0; i < 3; i++) {
  32273. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32274. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32275. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32276. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32277. }
  32278. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32279. };
  32280. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32281. this._currentEffect.setMatrix3x3(name, matrix);
  32282. };
  32283. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32284. this._currentEffect.setMatrix2x2(name, matrix);
  32285. };
  32286. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32287. // To match std140, matrix must be realigned
  32288. for (var i = 0; i < 2; i++) {
  32289. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32290. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32291. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32292. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32293. }
  32294. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32295. };
  32296. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32297. this._currentEffect.setFloat(name, x);
  32298. };
  32299. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32300. UniformBuffer._tempBuffer[0] = x;
  32301. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32302. };
  32303. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32304. if (suffix === void 0) { suffix = ""; }
  32305. this._currentEffect.setFloat2(name + suffix, x, y);
  32306. };
  32307. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32308. if (suffix === void 0) { suffix = ""; }
  32309. UniformBuffer._tempBuffer[0] = x;
  32310. UniformBuffer._tempBuffer[1] = y;
  32311. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32312. };
  32313. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32314. if (suffix === void 0) { suffix = ""; }
  32315. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32316. };
  32317. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32318. if (suffix === void 0) { suffix = ""; }
  32319. UniformBuffer._tempBuffer[0] = x;
  32320. UniformBuffer._tempBuffer[1] = y;
  32321. UniformBuffer._tempBuffer[2] = z;
  32322. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32323. };
  32324. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32325. if (suffix === void 0) { suffix = ""; }
  32326. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32327. };
  32328. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32329. if (suffix === void 0) { suffix = ""; }
  32330. UniformBuffer._tempBuffer[0] = x;
  32331. UniformBuffer._tempBuffer[1] = y;
  32332. UniformBuffer._tempBuffer[2] = z;
  32333. UniformBuffer._tempBuffer[3] = w;
  32334. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32335. };
  32336. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32337. this._currentEffect.setMatrix(name, mat);
  32338. };
  32339. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32340. this.updateUniform(name, mat.toArray(), 16);
  32341. };
  32342. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32343. this._currentEffect.setVector3(name, vector);
  32344. };
  32345. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32346. vector.toArray(UniformBuffer._tempBuffer);
  32347. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32348. };
  32349. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32350. this._currentEffect.setVector4(name, vector);
  32351. };
  32352. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32353. vector.toArray(UniformBuffer._tempBuffer);
  32354. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32355. };
  32356. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32357. if (suffix === void 0) { suffix = ""; }
  32358. this._currentEffect.setColor3(name + suffix, color);
  32359. };
  32360. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32361. if (suffix === void 0) { suffix = ""; }
  32362. color.toArray(UniformBuffer._tempBuffer);
  32363. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32364. };
  32365. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32366. if (suffix === void 0) { suffix = ""; }
  32367. this._currentEffect.setColor4(name + suffix, color, alpha);
  32368. };
  32369. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32370. if (suffix === void 0) { suffix = ""; }
  32371. color.toArray(UniformBuffer._tempBuffer);
  32372. UniformBuffer._tempBuffer[3] = alpha;
  32373. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32374. };
  32375. /**
  32376. * Sets a sampler uniform on the effect.
  32377. * @param {string} name Name of the sampler.
  32378. * @param {Texture} texture
  32379. */
  32380. UniformBuffer.prototype.setTexture = function (name, texture) {
  32381. this._currentEffect.setTexture(name, texture);
  32382. };
  32383. /**
  32384. * Directly updates the value of the uniform in the cache AND on the GPU.
  32385. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32386. * @param {number[]|Float32Array} data Flattened data
  32387. */
  32388. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32389. this.updateUniform(uniformName, data, data.length);
  32390. this.update();
  32391. };
  32392. /**
  32393. * Binds this uniform buffer to an effect.
  32394. * @param {Effect} effect
  32395. * @param {string} name Name of the uniform block in the shader.
  32396. */
  32397. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32398. this._currentEffect = effect;
  32399. if (this._noUBO || !this._buffer) {
  32400. return;
  32401. }
  32402. effect.bindUniformBuffer(this._buffer, name);
  32403. };
  32404. /**
  32405. * Disposes the uniform buffer.
  32406. */
  32407. UniformBuffer.prototype.dispose = function () {
  32408. if (this._noUBO) {
  32409. return;
  32410. }
  32411. var index = this._engine._uniformBuffers.indexOf(this);
  32412. if (index !== -1) {
  32413. this._engine._uniformBuffers.splice(index, 1);
  32414. }
  32415. if (!this._buffer) {
  32416. return;
  32417. }
  32418. if (this._engine._releaseBuffer(this._buffer)) {
  32419. this._buffer = null;
  32420. }
  32421. };
  32422. // Pool for avoiding memory leaks
  32423. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32424. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32425. return UniformBuffer;
  32426. }());
  32427. BABYLON.UniformBuffer = UniformBuffer;
  32428. })(BABYLON || (BABYLON = {}));
  32429. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32430. var BABYLON;
  32431. (function (BABYLON) {
  32432. var VertexData = /** @class */ (function () {
  32433. function VertexData() {
  32434. }
  32435. VertexData.prototype.set = function (data, kind) {
  32436. switch (kind) {
  32437. case BABYLON.VertexBuffer.PositionKind:
  32438. this.positions = data;
  32439. break;
  32440. case BABYLON.VertexBuffer.NormalKind:
  32441. this.normals = data;
  32442. break;
  32443. case BABYLON.VertexBuffer.TangentKind:
  32444. this.tangents = data;
  32445. break;
  32446. case BABYLON.VertexBuffer.UVKind:
  32447. this.uvs = data;
  32448. break;
  32449. case BABYLON.VertexBuffer.UV2Kind:
  32450. this.uvs2 = data;
  32451. break;
  32452. case BABYLON.VertexBuffer.UV3Kind:
  32453. this.uvs3 = data;
  32454. break;
  32455. case BABYLON.VertexBuffer.UV4Kind:
  32456. this.uvs4 = data;
  32457. break;
  32458. case BABYLON.VertexBuffer.UV5Kind:
  32459. this.uvs5 = data;
  32460. break;
  32461. case BABYLON.VertexBuffer.UV6Kind:
  32462. this.uvs6 = data;
  32463. break;
  32464. case BABYLON.VertexBuffer.ColorKind:
  32465. this.colors = data;
  32466. break;
  32467. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32468. this.matricesIndices = data;
  32469. break;
  32470. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32471. this.matricesWeights = data;
  32472. break;
  32473. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32474. this.matricesIndicesExtra = data;
  32475. break;
  32476. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32477. this.matricesWeightsExtra = data;
  32478. break;
  32479. }
  32480. };
  32481. /**
  32482. * Associates the vertexData to the passed Mesh.
  32483. * Sets it as updatable or not (default `false`).
  32484. * Returns the VertexData.
  32485. */
  32486. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32487. this._applyTo(mesh, updatable);
  32488. return this;
  32489. };
  32490. /**
  32491. * Associates the vertexData to the passed Geometry.
  32492. * Sets it as updatable or not (default `false`).
  32493. * Returns the VertexData.
  32494. */
  32495. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32496. this._applyTo(geometry, updatable);
  32497. return this;
  32498. };
  32499. /**
  32500. * Updates the associated mesh.
  32501. * Returns the VertexData.
  32502. */
  32503. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32504. this._update(mesh);
  32505. return this;
  32506. };
  32507. /**
  32508. * Updates the associated geometry.
  32509. * Returns the VertexData.
  32510. */
  32511. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32512. this._update(geometry);
  32513. return this;
  32514. };
  32515. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32516. if (updatable === void 0) { updatable = false; }
  32517. if (this.positions) {
  32518. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32519. }
  32520. if (this.normals) {
  32521. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32522. }
  32523. if (this.tangents) {
  32524. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32525. }
  32526. if (this.uvs) {
  32527. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32528. }
  32529. if (this.uvs2) {
  32530. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32531. }
  32532. if (this.uvs3) {
  32533. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32534. }
  32535. if (this.uvs4) {
  32536. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32537. }
  32538. if (this.uvs5) {
  32539. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32540. }
  32541. if (this.uvs6) {
  32542. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32543. }
  32544. if (this.colors) {
  32545. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32546. }
  32547. if (this.matricesIndices) {
  32548. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32549. }
  32550. if (this.matricesWeights) {
  32551. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32552. }
  32553. if (this.matricesIndicesExtra) {
  32554. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32555. }
  32556. if (this.matricesWeightsExtra) {
  32557. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32558. }
  32559. if (this.indices) {
  32560. meshOrGeometry.setIndices(this.indices, null, updatable);
  32561. }
  32562. return this;
  32563. };
  32564. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32565. if (this.positions) {
  32566. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32567. }
  32568. if (this.normals) {
  32569. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32570. }
  32571. if (this.tangents) {
  32572. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32573. }
  32574. if (this.uvs) {
  32575. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32576. }
  32577. if (this.uvs2) {
  32578. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32579. }
  32580. if (this.uvs3) {
  32581. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32582. }
  32583. if (this.uvs4) {
  32584. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32585. }
  32586. if (this.uvs5) {
  32587. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32588. }
  32589. if (this.uvs6) {
  32590. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32591. }
  32592. if (this.colors) {
  32593. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32594. }
  32595. if (this.matricesIndices) {
  32596. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32597. }
  32598. if (this.matricesWeights) {
  32599. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32600. }
  32601. if (this.matricesIndicesExtra) {
  32602. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32603. }
  32604. if (this.matricesWeightsExtra) {
  32605. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32606. }
  32607. if (this.indices) {
  32608. meshOrGeometry.setIndices(this.indices, null);
  32609. }
  32610. return this;
  32611. };
  32612. /**
  32613. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32614. * Returns the VertexData.
  32615. */
  32616. VertexData.prototype.transform = function (matrix) {
  32617. var transformed = BABYLON.Vector3.Zero();
  32618. var index;
  32619. if (this.positions) {
  32620. var position = BABYLON.Vector3.Zero();
  32621. for (index = 0; index < this.positions.length; index += 3) {
  32622. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32623. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32624. this.positions[index] = transformed.x;
  32625. this.positions[index + 1] = transformed.y;
  32626. this.positions[index + 2] = transformed.z;
  32627. }
  32628. }
  32629. if (this.normals) {
  32630. var normal = BABYLON.Vector3.Zero();
  32631. for (index = 0; index < this.normals.length; index += 3) {
  32632. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32633. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32634. this.normals[index] = transformed.x;
  32635. this.normals[index + 1] = transformed.y;
  32636. this.normals[index + 2] = transformed.z;
  32637. }
  32638. }
  32639. if (this.tangents) {
  32640. var tangent = BABYLON.Vector4.Zero();
  32641. var tangentTransformed = BABYLON.Vector4.Zero();
  32642. for (index = 0; index < this.tangents.length; index += 4) {
  32643. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32644. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32645. this.tangents[index] = tangentTransformed.x;
  32646. this.tangents[index + 1] = tangentTransformed.y;
  32647. this.tangents[index + 2] = tangentTransformed.z;
  32648. this.tangents[index + 3] = tangentTransformed.w;
  32649. }
  32650. }
  32651. return this;
  32652. };
  32653. /**
  32654. * Merges the passed VertexData into the current one.
  32655. * Returns the modified VertexData.
  32656. */
  32657. VertexData.prototype.merge = function (other) {
  32658. this._validate();
  32659. other._validate();
  32660. if (!this.normals !== !other.normals ||
  32661. !this.tangents !== !other.tangents ||
  32662. !this.uvs !== !other.uvs ||
  32663. !this.uvs2 !== !other.uvs2 ||
  32664. !this.uvs3 !== !other.uvs3 ||
  32665. !this.uvs4 !== !other.uvs4 ||
  32666. !this.uvs5 !== !other.uvs5 ||
  32667. !this.uvs6 !== !other.uvs6 ||
  32668. !this.colors !== !other.colors ||
  32669. !this.matricesIndices !== !other.matricesIndices ||
  32670. !this.matricesWeights !== !other.matricesWeights ||
  32671. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32672. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32673. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32674. }
  32675. if (other.indices) {
  32676. if (!this.indices) {
  32677. this.indices = [];
  32678. }
  32679. var offset = this.positions ? this.positions.length / 3 : 0;
  32680. for (var index = 0; index < other.indices.length; index++) {
  32681. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32682. this.indices.push(other.indices[index] + offset);
  32683. }
  32684. }
  32685. this.positions = this._mergeElement(this.positions, other.positions);
  32686. this.normals = this._mergeElement(this.normals, other.normals);
  32687. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32688. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32689. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32690. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32691. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32692. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32693. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32694. this.colors = this._mergeElement(this.colors, other.colors);
  32695. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32696. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32697. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32698. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32699. return this;
  32700. };
  32701. VertexData.prototype._mergeElement = function (source, other) {
  32702. if (!source) {
  32703. return other;
  32704. }
  32705. if (!other) {
  32706. return source;
  32707. }
  32708. var len = other.length + source.length;
  32709. var isSrcTypedArray = source instanceof Float32Array;
  32710. var isOthTypedArray = other instanceof Float32Array;
  32711. // use non-loop method when the source is Float32Array
  32712. if (isSrcTypedArray) {
  32713. var ret32 = new Float32Array(len);
  32714. ret32.set(source);
  32715. ret32.set(other, source.length);
  32716. return ret32;
  32717. // source is number[], when other is also use concat
  32718. }
  32719. else if (!isOthTypedArray) {
  32720. return source.concat(other);
  32721. // source is a number[], but other is a Float32Array, loop required
  32722. }
  32723. else {
  32724. var ret = source.slice(0); // copy source to a separate array
  32725. for (var i = 0, len = other.length; i < len; i++) {
  32726. ret.push(other[i]);
  32727. }
  32728. return ret;
  32729. }
  32730. };
  32731. VertexData.prototype._validate = function () {
  32732. if (!this.positions) {
  32733. throw new Error("Positions are required");
  32734. }
  32735. var getElementCount = function (kind, values) {
  32736. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32737. if ((values.length % stride) !== 0) {
  32738. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32739. }
  32740. return values.length / stride;
  32741. };
  32742. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32743. var validateElementCount = function (kind, values) {
  32744. var elementCount = getElementCount(kind, values);
  32745. if (elementCount !== positionsElementCount) {
  32746. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32747. }
  32748. };
  32749. if (this.normals)
  32750. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32751. if (this.tangents)
  32752. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32753. if (this.uvs)
  32754. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32755. if (this.uvs2)
  32756. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32757. if (this.uvs3)
  32758. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32759. if (this.uvs4)
  32760. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32761. if (this.uvs5)
  32762. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32763. if (this.uvs6)
  32764. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32765. if (this.colors)
  32766. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32767. if (this.matricesIndices)
  32768. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32769. if (this.matricesWeights)
  32770. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32771. if (this.matricesIndicesExtra)
  32772. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32773. if (this.matricesWeightsExtra)
  32774. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32775. };
  32776. /**
  32777. * Serializes the VertexData.
  32778. * Returns a serialized object.
  32779. */
  32780. VertexData.prototype.serialize = function () {
  32781. var serializationObject = this.serialize();
  32782. if (this.positions) {
  32783. serializationObject.positions = this.positions;
  32784. }
  32785. if (this.normals) {
  32786. serializationObject.normals = this.normals;
  32787. }
  32788. if (this.tangents) {
  32789. serializationObject.tangents = this.tangents;
  32790. }
  32791. if (this.uvs) {
  32792. serializationObject.uvs = this.uvs;
  32793. }
  32794. if (this.uvs2) {
  32795. serializationObject.uvs2 = this.uvs2;
  32796. }
  32797. if (this.uvs3) {
  32798. serializationObject.uvs3 = this.uvs3;
  32799. }
  32800. if (this.uvs4) {
  32801. serializationObject.uvs4 = this.uvs4;
  32802. }
  32803. if (this.uvs5) {
  32804. serializationObject.uvs5 = this.uvs5;
  32805. }
  32806. if (this.uvs6) {
  32807. serializationObject.uvs6 = this.uvs6;
  32808. }
  32809. if (this.colors) {
  32810. serializationObject.colors = this.colors;
  32811. }
  32812. if (this.matricesIndices) {
  32813. serializationObject.matricesIndices = this.matricesIndices;
  32814. serializationObject.matricesIndices._isExpanded = true;
  32815. }
  32816. if (this.matricesWeights) {
  32817. serializationObject.matricesWeights = this.matricesWeights;
  32818. }
  32819. if (this.matricesIndicesExtra) {
  32820. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32821. serializationObject.matricesIndicesExtra._isExpanded = true;
  32822. }
  32823. if (this.matricesWeightsExtra) {
  32824. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32825. }
  32826. serializationObject.indices = this.indices;
  32827. return serializationObject;
  32828. };
  32829. // Statics
  32830. /**
  32831. * Returns the object VertexData associated to the passed mesh.
  32832. */
  32833. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32834. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32835. };
  32836. /**
  32837. * Returns the object VertexData associated to the passed geometry.
  32838. */
  32839. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32840. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32841. };
  32842. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32843. var result = new VertexData();
  32844. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32845. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32846. }
  32847. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32848. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32849. }
  32850. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32851. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32852. }
  32853. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32854. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32855. }
  32856. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32857. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32858. }
  32859. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32860. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32861. }
  32862. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32863. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32864. }
  32865. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32866. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32867. }
  32868. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32869. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32870. }
  32871. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32872. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32873. }
  32874. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32875. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32876. }
  32877. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32878. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32879. }
  32880. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32881. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32882. }
  32883. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32884. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32885. }
  32886. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32887. return result;
  32888. };
  32889. /**
  32890. * Creates the vertexData of the Ribbon.
  32891. */
  32892. VertexData.CreateRibbon = function (options) {
  32893. var pathArray = options.pathArray;
  32894. var closeArray = options.closeArray || false;
  32895. var closePath = options.closePath || false;
  32896. var invertUV = options.invertUV || false;
  32897. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32898. var offset = options.offset || defaultOffset;
  32899. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32900. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32901. var customUV = options.uvs;
  32902. var customColors = options.colors;
  32903. var positions = [];
  32904. var indices = [];
  32905. var normals = [];
  32906. var uvs = [];
  32907. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32908. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32909. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32910. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32911. var minlg; // minimal length among all paths from pathArray
  32912. var lg = []; // array of path lengths : nb of vertex per path
  32913. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32914. var p; // path iterator
  32915. var i; // point iterator
  32916. var j; // point iterator
  32917. // if single path in pathArray
  32918. if (pathArray.length < 2) {
  32919. var ar1 = [];
  32920. var ar2 = [];
  32921. for (i = 0; i < pathArray[0].length - offset; i++) {
  32922. ar1.push(pathArray[0][i]);
  32923. ar2.push(pathArray[0][i + offset]);
  32924. }
  32925. pathArray = [ar1, ar2];
  32926. }
  32927. // positions and horizontal distances (u)
  32928. var idc = 0;
  32929. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32930. var path;
  32931. var l;
  32932. minlg = pathArray[0].length;
  32933. var vectlg;
  32934. var dist;
  32935. for (p = 0; p < pathArray.length; p++) {
  32936. uTotalDistance[p] = 0;
  32937. us[p] = [0];
  32938. path = pathArray[p];
  32939. l = path.length;
  32940. minlg = (minlg < l) ? minlg : l;
  32941. j = 0;
  32942. while (j < l) {
  32943. positions.push(path[j].x, path[j].y, path[j].z);
  32944. if (j > 0) {
  32945. vectlg = path[j].subtract(path[j - 1]).length();
  32946. dist = vectlg + uTotalDistance[p];
  32947. us[p].push(dist);
  32948. uTotalDistance[p] = dist;
  32949. }
  32950. j++;
  32951. }
  32952. if (closePath) {
  32953. j--;
  32954. positions.push(path[0].x, path[0].y, path[0].z);
  32955. vectlg = path[j].subtract(path[0]).length();
  32956. dist = vectlg + uTotalDistance[p];
  32957. us[p].push(dist);
  32958. uTotalDistance[p] = dist;
  32959. }
  32960. lg[p] = l + closePathCorr;
  32961. idx[p] = idc;
  32962. idc += (l + closePathCorr);
  32963. }
  32964. // vertical distances (v)
  32965. var path1;
  32966. var path2;
  32967. var vertex1 = null;
  32968. var vertex2 = null;
  32969. for (i = 0; i < minlg + closePathCorr; i++) {
  32970. vTotalDistance[i] = 0;
  32971. vs[i] = [0];
  32972. for (p = 0; p < pathArray.length - 1; p++) {
  32973. path1 = pathArray[p];
  32974. path2 = pathArray[p + 1];
  32975. if (i === minlg) {
  32976. vertex1 = path1[0];
  32977. vertex2 = path2[0];
  32978. }
  32979. else {
  32980. vertex1 = path1[i];
  32981. vertex2 = path2[i];
  32982. }
  32983. vectlg = vertex2.subtract(vertex1).length();
  32984. dist = vectlg + vTotalDistance[i];
  32985. vs[i].push(dist);
  32986. vTotalDistance[i] = dist;
  32987. }
  32988. if (closeArray && vertex2 && vertex1) {
  32989. path1 = pathArray[p];
  32990. path2 = pathArray[0];
  32991. if (i === minlg) {
  32992. vertex2 = path2[0];
  32993. }
  32994. vectlg = vertex2.subtract(vertex1).length();
  32995. dist = vectlg + vTotalDistance[i];
  32996. vTotalDistance[i] = dist;
  32997. }
  32998. }
  32999. // uvs
  33000. var u;
  33001. var v;
  33002. if (customUV) {
  33003. for (p = 0; p < customUV.length; p++) {
  33004. uvs.push(customUV[p].x, customUV[p].y);
  33005. }
  33006. }
  33007. else {
  33008. for (p = 0; p < pathArray.length; p++) {
  33009. for (i = 0; i < minlg + closePathCorr; i++) {
  33010. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33011. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33012. if (invertUV) {
  33013. uvs.push(v, u);
  33014. }
  33015. else {
  33016. uvs.push(u, v);
  33017. }
  33018. }
  33019. }
  33020. }
  33021. // indices
  33022. p = 0; // path index
  33023. var pi = 0; // positions array index
  33024. var l1 = lg[p] - 1; // path1 length
  33025. var l2 = lg[p + 1] - 1; // path2 length
  33026. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33027. var shft = idx[1] - idx[0]; // shift
  33028. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33029. while (pi <= min && p < path1nb) {
  33030. // 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
  33031. indices.push(pi, pi + shft, pi + 1);
  33032. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33033. pi += 1;
  33034. if (pi === min) {
  33035. p++;
  33036. if (p === lg.length - 1) {
  33037. shft = idx[0] - idx[p];
  33038. l1 = lg[p] - 1;
  33039. l2 = lg[0] - 1;
  33040. }
  33041. else {
  33042. shft = idx[p + 1] - idx[p];
  33043. l1 = lg[p] - 1;
  33044. l2 = lg[p + 1] - 1;
  33045. }
  33046. pi = idx[p];
  33047. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33048. }
  33049. }
  33050. // normals
  33051. VertexData.ComputeNormals(positions, indices, normals);
  33052. if (closePath) {
  33053. var indexFirst = 0;
  33054. var indexLast = 0;
  33055. for (p = 0; p < pathArray.length; p++) {
  33056. indexFirst = idx[p] * 3;
  33057. if (p + 1 < pathArray.length) {
  33058. indexLast = (idx[p + 1] - 1) * 3;
  33059. }
  33060. else {
  33061. indexLast = normals.length - 3;
  33062. }
  33063. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33064. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33065. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33066. normals[indexLast] = normals[indexFirst];
  33067. normals[indexLast + 1] = normals[indexFirst + 1];
  33068. normals[indexLast + 2] = normals[indexFirst + 2];
  33069. }
  33070. }
  33071. // sides
  33072. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33073. // Colors
  33074. var colors = null;
  33075. if (customColors) {
  33076. colors = new Float32Array(customColors.length * 4);
  33077. for (var c = 0; c < customColors.length; c++) {
  33078. colors[c * 4] = customColors[c].r;
  33079. colors[c * 4 + 1] = customColors[c].g;
  33080. colors[c * 4 + 2] = customColors[c].b;
  33081. colors[c * 4 + 3] = customColors[c].a;
  33082. }
  33083. }
  33084. // Result
  33085. var vertexData = new VertexData();
  33086. var positions32 = new Float32Array(positions);
  33087. var normals32 = new Float32Array(normals);
  33088. var uvs32 = new Float32Array(uvs);
  33089. vertexData.indices = indices;
  33090. vertexData.positions = positions32;
  33091. vertexData.normals = normals32;
  33092. vertexData.uvs = uvs32;
  33093. if (colors) {
  33094. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33095. }
  33096. if (closePath) {
  33097. vertexData._idx = idx;
  33098. }
  33099. return vertexData;
  33100. };
  33101. /**
  33102. * Creates the VertexData of the Box.
  33103. */
  33104. VertexData.CreateBox = function (options) {
  33105. var normalsSource = [
  33106. new BABYLON.Vector3(0, 0, 1),
  33107. new BABYLON.Vector3(0, 0, -1),
  33108. new BABYLON.Vector3(1, 0, 0),
  33109. new BABYLON.Vector3(-1, 0, 0),
  33110. new BABYLON.Vector3(0, 1, 0),
  33111. new BABYLON.Vector3(0, -1, 0)
  33112. ];
  33113. var indices = [];
  33114. var positions = [];
  33115. var normals = [];
  33116. var uvs = [];
  33117. var width = options.width || options.size || 1;
  33118. var height = options.height || options.size || 1;
  33119. var depth = options.depth || options.size || 1;
  33120. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33121. var faceUV = options.faceUV || new Array(6);
  33122. var faceColors = options.faceColors;
  33123. var colors = [];
  33124. // default face colors and UV if undefined
  33125. for (var f = 0; f < 6; f++) {
  33126. if (faceUV[f] === undefined) {
  33127. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33128. }
  33129. if (faceColors && faceColors[f] === undefined) {
  33130. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33131. }
  33132. }
  33133. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33134. // Create each face in turn.
  33135. for (var index = 0; index < normalsSource.length; index++) {
  33136. var normal = normalsSource[index];
  33137. // Get two vectors perpendicular to the face normal and to each other.
  33138. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33139. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33140. // Six indices (two triangles) per face.
  33141. var verticesLength = positions.length / 3;
  33142. indices.push(verticesLength);
  33143. indices.push(verticesLength + 1);
  33144. indices.push(verticesLength + 2);
  33145. indices.push(verticesLength);
  33146. indices.push(verticesLength + 2);
  33147. indices.push(verticesLength + 3);
  33148. // Four vertices per face.
  33149. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33150. positions.push(vertex.x, vertex.y, vertex.z);
  33151. normals.push(normal.x, normal.y, normal.z);
  33152. uvs.push(faceUV[index].z, faceUV[index].w);
  33153. if (faceColors) {
  33154. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33155. }
  33156. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33157. positions.push(vertex.x, vertex.y, vertex.z);
  33158. normals.push(normal.x, normal.y, normal.z);
  33159. uvs.push(faceUV[index].x, faceUV[index].w);
  33160. if (faceColors) {
  33161. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33162. }
  33163. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33164. positions.push(vertex.x, vertex.y, vertex.z);
  33165. normals.push(normal.x, normal.y, normal.z);
  33166. uvs.push(faceUV[index].x, faceUV[index].y);
  33167. if (faceColors) {
  33168. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33169. }
  33170. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33171. positions.push(vertex.x, vertex.y, vertex.z);
  33172. normals.push(normal.x, normal.y, normal.z);
  33173. uvs.push(faceUV[index].z, faceUV[index].y);
  33174. if (faceColors) {
  33175. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33176. }
  33177. }
  33178. // sides
  33179. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33180. // Result
  33181. var vertexData = new VertexData();
  33182. vertexData.indices = indices;
  33183. vertexData.positions = positions;
  33184. vertexData.normals = normals;
  33185. vertexData.uvs = uvs;
  33186. if (faceColors) {
  33187. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33188. vertexData.colors = totalColors;
  33189. }
  33190. return vertexData;
  33191. };
  33192. /**
  33193. * Creates the VertexData of the Sphere.
  33194. */
  33195. VertexData.CreateSphere = function (options) {
  33196. var segments = options.segments || 32;
  33197. var diameterX = options.diameterX || options.diameter || 1;
  33198. var diameterY = options.diameterY || options.diameter || 1;
  33199. var diameterZ = options.diameterZ || options.diameter || 1;
  33200. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33201. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33202. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33203. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33204. var totalZRotationSteps = 2 + segments;
  33205. var totalYRotationSteps = 2 * totalZRotationSteps;
  33206. var indices = [];
  33207. var positions = [];
  33208. var normals = [];
  33209. var uvs = [];
  33210. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33211. var normalizedZ = zRotationStep / totalZRotationSteps;
  33212. var angleZ = normalizedZ * Math.PI * slice;
  33213. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33214. var normalizedY = yRotationStep / totalYRotationSteps;
  33215. var angleY = normalizedY * Math.PI * 2 * arc;
  33216. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33217. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33218. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33219. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33220. var vertex = complete.multiply(radius);
  33221. var normal = complete.divide(radius).normalize();
  33222. positions.push(vertex.x, vertex.y, vertex.z);
  33223. normals.push(normal.x, normal.y, normal.z);
  33224. uvs.push(normalizedY, normalizedZ);
  33225. }
  33226. if (zRotationStep > 0) {
  33227. var verticesCount = positions.length / 3;
  33228. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33229. indices.push((firstIndex));
  33230. indices.push((firstIndex + 1));
  33231. indices.push(firstIndex + totalYRotationSteps + 1);
  33232. indices.push((firstIndex + totalYRotationSteps + 1));
  33233. indices.push((firstIndex + 1));
  33234. indices.push((firstIndex + totalYRotationSteps + 2));
  33235. }
  33236. }
  33237. }
  33238. // Sides
  33239. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33240. // Result
  33241. var vertexData = new VertexData();
  33242. vertexData.indices = indices;
  33243. vertexData.positions = positions;
  33244. vertexData.normals = normals;
  33245. vertexData.uvs = uvs;
  33246. return vertexData;
  33247. };
  33248. /**
  33249. * Creates the VertexData of the Cylinder or Cone.
  33250. */
  33251. VertexData.CreateCylinder = function (options) {
  33252. var height = options.height || 2;
  33253. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33254. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33255. var tessellation = options.tessellation || 24;
  33256. var subdivisions = options.subdivisions || 1;
  33257. var hasRings = options.hasRings ? true : false;
  33258. var enclose = options.enclose ? true : false;
  33259. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33260. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33261. var faceUV = options.faceUV || new Array(3);
  33262. var faceColors = options.faceColors;
  33263. // default face colors and UV if undefined
  33264. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33265. var ringNb = (hasRings) ? subdivisions : 1;
  33266. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33267. var f;
  33268. for (f = 0; f < surfaceNb; f++) {
  33269. if (faceColors && faceColors[f] === undefined) {
  33270. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33271. }
  33272. }
  33273. for (f = 0; f < surfaceNb; f++) {
  33274. if (faceUV && faceUV[f] === undefined) {
  33275. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33276. }
  33277. }
  33278. var indices = new Array();
  33279. var positions = new Array();
  33280. var normals = new Array();
  33281. var uvs = new Array();
  33282. var colors = new Array();
  33283. var angle_step = Math.PI * 2 * arc / tessellation;
  33284. var angle;
  33285. var h;
  33286. var radius;
  33287. var tan = (diameterBottom - diameterTop) / 2 / height;
  33288. var ringVertex = BABYLON.Vector3.Zero();
  33289. var ringNormal = BABYLON.Vector3.Zero();
  33290. var ringFirstVertex = BABYLON.Vector3.Zero();
  33291. var ringFirstNormal = BABYLON.Vector3.Zero();
  33292. var quadNormal = BABYLON.Vector3.Zero();
  33293. var Y = BABYLON.Axis.Y;
  33294. // positions, normals, uvs
  33295. var i;
  33296. var j;
  33297. var r;
  33298. var ringIdx = 1;
  33299. var s = 1; // surface index
  33300. var cs = 0;
  33301. var v = 0;
  33302. for (i = 0; i <= subdivisions; i++) {
  33303. h = i / subdivisions;
  33304. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33305. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33306. for (r = 0; r < ringIdx; r++) {
  33307. if (hasRings) {
  33308. s += r;
  33309. }
  33310. if (enclose) {
  33311. s += 2 * r;
  33312. }
  33313. for (j = 0; j <= tessellation; j++) {
  33314. angle = j * angle_step;
  33315. // position
  33316. ringVertex.x = Math.cos(-angle) * radius;
  33317. ringVertex.y = -height / 2 + h * height;
  33318. ringVertex.z = Math.sin(-angle) * radius;
  33319. // normal
  33320. if (diameterTop === 0 && i === subdivisions) {
  33321. // if no top cap, reuse former normals
  33322. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33323. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33324. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33325. }
  33326. else {
  33327. ringNormal.x = ringVertex.x;
  33328. ringNormal.z = ringVertex.z;
  33329. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33330. ringNormal.normalize();
  33331. }
  33332. // keep first ring vertex values for enclose
  33333. if (j === 0) {
  33334. ringFirstVertex.copyFrom(ringVertex);
  33335. ringFirstNormal.copyFrom(ringNormal);
  33336. }
  33337. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33338. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33339. if (hasRings) {
  33340. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33341. }
  33342. else {
  33343. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33344. }
  33345. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33346. if (faceColors) {
  33347. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33348. }
  33349. }
  33350. // if enclose, add four vertices and their dedicated normals
  33351. if (arc !== 1 && enclose) {
  33352. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33353. positions.push(0, ringVertex.y, 0);
  33354. positions.push(0, ringVertex.y, 0);
  33355. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33356. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33357. quadNormal.normalize();
  33358. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33359. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33360. quadNormal.normalize();
  33361. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33362. if (hasRings) {
  33363. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33364. }
  33365. else {
  33366. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33367. }
  33368. uvs.push(faceUV[s + 1].x, v);
  33369. uvs.push(faceUV[s + 1].z, v);
  33370. if (hasRings) {
  33371. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33372. }
  33373. else {
  33374. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33375. }
  33376. uvs.push(faceUV[s + 2].x, v);
  33377. uvs.push(faceUV[s + 2].z, v);
  33378. if (faceColors) {
  33379. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33380. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33381. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33382. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33383. }
  33384. }
  33385. if (cs !== s) {
  33386. cs = s;
  33387. }
  33388. }
  33389. }
  33390. // indices
  33391. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33392. var s;
  33393. i = 0;
  33394. for (s = 0; s < subdivisions; s++) {
  33395. var i0 = 0;
  33396. var i1 = 0;
  33397. var i2 = 0;
  33398. var i3 = 0;
  33399. for (j = 0; j < tessellation; j++) {
  33400. i0 = i * (e + 1) + j;
  33401. i1 = (i + 1) * (e + 1) + j;
  33402. i2 = i * (e + 1) + (j + 1);
  33403. i3 = (i + 1) * (e + 1) + (j + 1);
  33404. indices.push(i0, i1, i2);
  33405. indices.push(i3, i2, i1);
  33406. }
  33407. if (arc !== 1 && enclose) {
  33408. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33409. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33410. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33411. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33412. }
  33413. i = (hasRings) ? (i + 2) : (i + 1);
  33414. }
  33415. // Caps
  33416. var createCylinderCap = function (isTop) {
  33417. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33418. if (radius === 0) {
  33419. return;
  33420. }
  33421. // Cap positions, normals & uvs
  33422. var angle;
  33423. var circleVector;
  33424. var i;
  33425. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33426. var c = null;
  33427. if (faceColors) {
  33428. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33429. }
  33430. // cap center
  33431. var vbase = positions.length / 3;
  33432. var offset = isTop ? height / 2 : -height / 2;
  33433. var center = new BABYLON.Vector3(0, offset, 0);
  33434. positions.push(center.x, center.y, center.z);
  33435. normals.push(0, isTop ? 1 : -1, 0);
  33436. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33437. if (c) {
  33438. colors.push(c.r, c.g, c.b, c.a);
  33439. }
  33440. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33441. for (i = 0; i <= tessellation; i++) {
  33442. angle = Math.PI * 2 * i * arc / tessellation;
  33443. var cos = Math.cos(-angle);
  33444. var sin = Math.sin(-angle);
  33445. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33446. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33447. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33448. normals.push(0, isTop ? 1 : -1, 0);
  33449. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33450. if (c) {
  33451. colors.push(c.r, c.g, c.b, c.a);
  33452. }
  33453. }
  33454. // Cap indices
  33455. for (i = 0; i < tessellation; i++) {
  33456. if (!isTop) {
  33457. indices.push(vbase);
  33458. indices.push(vbase + (i + 1));
  33459. indices.push(vbase + (i + 2));
  33460. }
  33461. else {
  33462. indices.push(vbase);
  33463. indices.push(vbase + (i + 2));
  33464. indices.push(vbase + (i + 1));
  33465. }
  33466. }
  33467. };
  33468. // add caps to geometry
  33469. createCylinderCap(false);
  33470. createCylinderCap(true);
  33471. // Sides
  33472. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33473. var vertexData = new VertexData();
  33474. vertexData.indices = indices;
  33475. vertexData.positions = positions;
  33476. vertexData.normals = normals;
  33477. vertexData.uvs = uvs;
  33478. if (faceColors) {
  33479. vertexData.colors = colors;
  33480. }
  33481. return vertexData;
  33482. };
  33483. /**
  33484. * Creates the VertexData of the Torus.
  33485. */
  33486. VertexData.CreateTorus = function (options) {
  33487. var indices = [];
  33488. var positions = [];
  33489. var normals = [];
  33490. var uvs = [];
  33491. var diameter = options.diameter || 1;
  33492. var thickness = options.thickness || 0.5;
  33493. var tessellation = options.tessellation || 16;
  33494. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33495. var stride = tessellation + 1;
  33496. for (var i = 0; i <= tessellation; i++) {
  33497. var u = i / tessellation;
  33498. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33499. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33500. for (var j = 0; j <= tessellation; j++) {
  33501. var v = 1 - j / tessellation;
  33502. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33503. var dx = Math.cos(innerAngle);
  33504. var dy = Math.sin(innerAngle);
  33505. // Create a vertex.
  33506. var normal = new BABYLON.Vector3(dx, dy, 0);
  33507. var position = normal.scale(thickness / 2);
  33508. var textureCoordinate = new BABYLON.Vector2(u, v);
  33509. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33510. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33511. positions.push(position.x, position.y, position.z);
  33512. normals.push(normal.x, normal.y, normal.z);
  33513. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33514. // And create indices for two triangles.
  33515. var nextI = (i + 1) % stride;
  33516. var nextJ = (j + 1) % stride;
  33517. indices.push(i * stride + j);
  33518. indices.push(i * stride + nextJ);
  33519. indices.push(nextI * stride + j);
  33520. indices.push(i * stride + nextJ);
  33521. indices.push(nextI * stride + nextJ);
  33522. indices.push(nextI * stride + j);
  33523. }
  33524. }
  33525. // Sides
  33526. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33527. // Result
  33528. var vertexData = new VertexData();
  33529. vertexData.indices = indices;
  33530. vertexData.positions = positions;
  33531. vertexData.normals = normals;
  33532. vertexData.uvs = uvs;
  33533. return vertexData;
  33534. };
  33535. /**
  33536. * Creates the VertexData of the LineSystem.
  33537. */
  33538. VertexData.CreateLineSystem = function (options) {
  33539. var indices = [];
  33540. var positions = [];
  33541. var lines = options.lines;
  33542. var colors = options.colors;
  33543. var vertexColors = [];
  33544. var idx = 0;
  33545. for (var l = 0; l < lines.length; l++) {
  33546. var points = lines[l];
  33547. for (var index = 0; index < points.length; index++) {
  33548. positions.push(points[index].x, points[index].y, points[index].z);
  33549. if (colors) {
  33550. var color = colors[l];
  33551. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33552. }
  33553. if (index > 0) {
  33554. indices.push(idx - 1);
  33555. indices.push(idx);
  33556. }
  33557. idx++;
  33558. }
  33559. }
  33560. var vertexData = new VertexData();
  33561. vertexData.indices = indices;
  33562. vertexData.positions = positions;
  33563. if (colors) {
  33564. vertexData.colors = vertexColors;
  33565. }
  33566. return vertexData;
  33567. };
  33568. /**
  33569. * Create the VertexData of the DashedLines.
  33570. */
  33571. VertexData.CreateDashedLines = function (options) {
  33572. var dashSize = options.dashSize || 3;
  33573. var gapSize = options.gapSize || 1;
  33574. var dashNb = options.dashNb || 200;
  33575. var points = options.points;
  33576. var positions = new Array();
  33577. var indices = new Array();
  33578. var curvect = BABYLON.Vector3.Zero();
  33579. var lg = 0;
  33580. var nb = 0;
  33581. var shft = 0;
  33582. var dashshft = 0;
  33583. var curshft = 0;
  33584. var idx = 0;
  33585. var i = 0;
  33586. for (i = 0; i < points.length - 1; i++) {
  33587. points[i + 1].subtractToRef(points[i], curvect);
  33588. lg += curvect.length();
  33589. }
  33590. shft = lg / dashNb;
  33591. dashshft = dashSize * shft / (dashSize + gapSize);
  33592. for (i = 0; i < points.length - 1; i++) {
  33593. points[i + 1].subtractToRef(points[i], curvect);
  33594. nb = Math.floor(curvect.length() / shft);
  33595. curvect.normalize();
  33596. for (var j = 0; j < nb; j++) {
  33597. curshft = shft * j;
  33598. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33599. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33600. indices.push(idx, idx + 1);
  33601. idx += 2;
  33602. }
  33603. }
  33604. // Result
  33605. var vertexData = new VertexData();
  33606. vertexData.positions = positions;
  33607. vertexData.indices = indices;
  33608. return vertexData;
  33609. };
  33610. /**
  33611. * Creates the VertexData of the Ground.
  33612. */
  33613. VertexData.CreateGround = function (options) {
  33614. var indices = [];
  33615. var positions = [];
  33616. var normals = [];
  33617. var uvs = [];
  33618. var row, col;
  33619. var width = options.width || 1;
  33620. var height = options.height || 1;
  33621. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33622. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33623. for (row = 0; row <= subdivisionsY; row++) {
  33624. for (col = 0; col <= subdivisionsX; col++) {
  33625. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33626. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33627. positions.push(position.x, position.y, position.z);
  33628. normals.push(normal.x, normal.y, normal.z);
  33629. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33630. }
  33631. }
  33632. for (row = 0; row < subdivisionsY; row++) {
  33633. for (col = 0; col < subdivisionsX; col++) {
  33634. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33635. indices.push(col + 1 + row * (subdivisionsX + 1));
  33636. indices.push(col + row * (subdivisionsX + 1));
  33637. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33638. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33639. indices.push(col + row * (subdivisionsX + 1));
  33640. }
  33641. }
  33642. // Result
  33643. var vertexData = new VertexData();
  33644. vertexData.indices = indices;
  33645. vertexData.positions = positions;
  33646. vertexData.normals = normals;
  33647. vertexData.uvs = uvs;
  33648. return vertexData;
  33649. };
  33650. /**
  33651. * Creates the VertexData of the TiledGround.
  33652. */
  33653. VertexData.CreateTiledGround = function (options) {
  33654. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33655. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33656. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33657. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33658. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33659. var precision = options.precision || { w: 1, h: 1 };
  33660. var indices = new Array();
  33661. var positions = new Array();
  33662. var normals = new Array();
  33663. var uvs = new Array();
  33664. var row, col, tileRow, tileCol;
  33665. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33666. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33667. precision.w = (precision.w < 1) ? 1 : precision.w;
  33668. precision.h = (precision.h < 1) ? 1 : precision.h;
  33669. var tileSize = {
  33670. 'w': (xmax - xmin) / subdivisions.w,
  33671. 'h': (zmax - zmin) / subdivisions.h
  33672. };
  33673. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33674. // Indices
  33675. var base = positions.length / 3;
  33676. var rowLength = precision.w + 1;
  33677. for (row = 0; row < precision.h; row++) {
  33678. for (col = 0; col < precision.w; col++) {
  33679. var square = [
  33680. base + col + row * rowLength,
  33681. base + (col + 1) + row * rowLength,
  33682. base + (col + 1) + (row + 1) * rowLength,
  33683. base + col + (row + 1) * rowLength
  33684. ];
  33685. indices.push(square[1]);
  33686. indices.push(square[2]);
  33687. indices.push(square[3]);
  33688. indices.push(square[0]);
  33689. indices.push(square[1]);
  33690. indices.push(square[3]);
  33691. }
  33692. }
  33693. // Position, normals and uvs
  33694. var position = BABYLON.Vector3.Zero();
  33695. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33696. for (row = 0; row <= precision.h; row++) {
  33697. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33698. for (col = 0; col <= precision.w; col++) {
  33699. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33700. position.y = 0;
  33701. positions.push(position.x, position.y, position.z);
  33702. normals.push(normal.x, normal.y, normal.z);
  33703. uvs.push(col / precision.w, row / precision.h);
  33704. }
  33705. }
  33706. }
  33707. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33708. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33709. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33710. }
  33711. }
  33712. // Result
  33713. var vertexData = new VertexData();
  33714. vertexData.indices = indices;
  33715. vertexData.positions = positions;
  33716. vertexData.normals = normals;
  33717. vertexData.uvs = uvs;
  33718. return vertexData;
  33719. };
  33720. /**
  33721. * Creates the VertexData of the Ground designed from a heightmap.
  33722. */
  33723. VertexData.CreateGroundFromHeightMap = function (options) {
  33724. var indices = [];
  33725. var positions = [];
  33726. var normals = [];
  33727. var uvs = [];
  33728. var row, col;
  33729. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33730. // Vertices
  33731. for (row = 0; row <= options.subdivisions; row++) {
  33732. for (col = 0; col <= options.subdivisions; col++) {
  33733. 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));
  33734. // Compute height
  33735. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33736. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33737. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33738. var r = options.buffer[pos] / 255.0;
  33739. var g = options.buffer[pos + 1] / 255.0;
  33740. var b = options.buffer[pos + 2] / 255.0;
  33741. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33742. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33743. // Add vertex
  33744. positions.push(position.x, position.y, position.z);
  33745. normals.push(0, 0, 0);
  33746. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33747. }
  33748. }
  33749. // Indices
  33750. for (row = 0; row < options.subdivisions; row++) {
  33751. for (col = 0; col < options.subdivisions; col++) {
  33752. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33753. indices.push(col + 1 + row * (options.subdivisions + 1));
  33754. indices.push(col + row * (options.subdivisions + 1));
  33755. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33756. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33757. indices.push(col + row * (options.subdivisions + 1));
  33758. }
  33759. }
  33760. // Normals
  33761. VertexData.ComputeNormals(positions, indices, normals);
  33762. // Result
  33763. var vertexData = new VertexData();
  33764. vertexData.indices = indices;
  33765. vertexData.positions = positions;
  33766. vertexData.normals = normals;
  33767. vertexData.uvs = uvs;
  33768. return vertexData;
  33769. };
  33770. /**
  33771. * Creates the VertexData of the Plane.
  33772. */
  33773. VertexData.CreatePlane = function (options) {
  33774. var indices = [];
  33775. var positions = [];
  33776. var normals = [];
  33777. var uvs = [];
  33778. var width = options.width || options.size || 1;
  33779. var height = options.height || options.size || 1;
  33780. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33781. // Vertices
  33782. var halfWidth = width / 2.0;
  33783. var halfHeight = height / 2.0;
  33784. positions.push(-halfWidth, -halfHeight, 0);
  33785. normals.push(0, 0, -1.0);
  33786. uvs.push(0.0, 0.0);
  33787. positions.push(halfWidth, -halfHeight, 0);
  33788. normals.push(0, 0, -1.0);
  33789. uvs.push(1.0, 0.0);
  33790. positions.push(halfWidth, halfHeight, 0);
  33791. normals.push(0, 0, -1.0);
  33792. uvs.push(1.0, 1.0);
  33793. positions.push(-halfWidth, halfHeight, 0);
  33794. normals.push(0, 0, -1.0);
  33795. uvs.push(0.0, 1.0);
  33796. // Indices
  33797. indices.push(0);
  33798. indices.push(1);
  33799. indices.push(2);
  33800. indices.push(0);
  33801. indices.push(2);
  33802. indices.push(3);
  33803. // Sides
  33804. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33805. // Result
  33806. var vertexData = new VertexData();
  33807. vertexData.indices = indices;
  33808. vertexData.positions = positions;
  33809. vertexData.normals = normals;
  33810. vertexData.uvs = uvs;
  33811. return vertexData;
  33812. };
  33813. /**
  33814. * Creates the VertexData of the Disc or regular Polygon.
  33815. */
  33816. VertexData.CreateDisc = function (options) {
  33817. var positions = new Array();
  33818. var indices = new Array();
  33819. var normals = new Array();
  33820. var uvs = new Array();
  33821. var radius = options.radius || 0.5;
  33822. var tessellation = options.tessellation || 64;
  33823. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33824. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33825. // positions and uvs
  33826. positions.push(0, 0, 0); // disc center first
  33827. uvs.push(0.5, 0.5);
  33828. var theta = Math.PI * 2 * arc;
  33829. var step = theta / tessellation;
  33830. for (var a = 0; a < theta; a += step) {
  33831. var x = Math.cos(a);
  33832. var y = Math.sin(a);
  33833. var u = (x + 1) / 2;
  33834. var v = (1 - y) / 2;
  33835. positions.push(radius * x, radius * y, 0);
  33836. uvs.push(u, v);
  33837. }
  33838. if (arc === 1) {
  33839. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33840. uvs.push(uvs[2], uvs[3]);
  33841. }
  33842. //indices
  33843. var vertexNb = positions.length / 3;
  33844. for (var i = 1; i < vertexNb - 1; i++) {
  33845. indices.push(i + 1, 0, i);
  33846. }
  33847. // result
  33848. VertexData.ComputeNormals(positions, indices, normals);
  33849. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33850. var vertexData = new VertexData();
  33851. vertexData.indices = indices;
  33852. vertexData.positions = positions;
  33853. vertexData.normals = normals;
  33854. vertexData.uvs = uvs;
  33855. return vertexData;
  33856. };
  33857. /**
  33858. * Re-creates the VertexData of the Polygon for sideOrientation.
  33859. */
  33860. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33861. var faceUV = fUV || new Array(3);
  33862. var faceColors = fColors;
  33863. var colors = [];
  33864. // default face colors and UV if undefined
  33865. for (var f = 0; f < 3; f++) {
  33866. if (faceUV[f] === undefined) {
  33867. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33868. }
  33869. if (faceColors && faceColors[f] === undefined) {
  33870. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33871. }
  33872. }
  33873. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33874. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33875. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33876. var indices = polygon.getIndices();
  33877. // set face colours and textures
  33878. var idx = 0;
  33879. var face = 0;
  33880. for (var index = 0; index < normals.length; index += 3) {
  33881. //Edge Face no. 1
  33882. if (Math.abs(normals[index + 1]) < 0.001) {
  33883. face = 1;
  33884. }
  33885. //Top Face no. 0
  33886. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33887. face = 0;
  33888. }
  33889. //Bottom Face no. 2
  33890. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33891. face = 2;
  33892. }
  33893. idx = index / 3;
  33894. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33895. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33896. if (faceColors) {
  33897. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33898. }
  33899. }
  33900. // sides
  33901. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33902. // Result
  33903. var vertexData = new VertexData();
  33904. vertexData.indices = indices;
  33905. vertexData.positions = positions;
  33906. vertexData.normals = normals;
  33907. vertexData.uvs = uvs;
  33908. if (faceColors) {
  33909. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33910. vertexData.colors = totalColors;
  33911. }
  33912. return vertexData;
  33913. };
  33914. /**
  33915. * Creates the VertexData of the IcoSphere.
  33916. */
  33917. VertexData.CreateIcoSphere = function (options) {
  33918. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33919. var radius = options.radius || 1;
  33920. var flat = (options.flat === undefined) ? true : options.flat;
  33921. var subdivisions = options.subdivisions || 4;
  33922. var radiusX = options.radiusX || radius;
  33923. var radiusY = options.radiusY || radius;
  33924. var radiusZ = options.radiusZ || radius;
  33925. var t = (1 + Math.sqrt(5)) / 2;
  33926. // 12 vertex x,y,z
  33927. var ico_vertices = [
  33928. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33929. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33930. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33931. ];
  33932. // index of 3 vertex makes a face of icopshere
  33933. var ico_indices = [
  33934. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33935. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33936. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33937. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33938. ];
  33939. // vertex for uv have aliased position, not for UV
  33940. var vertices_unalias_id = [
  33941. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33942. // vertex alias
  33943. 0,
  33944. 2,
  33945. 3,
  33946. 3,
  33947. 3,
  33948. 4,
  33949. 7,
  33950. 8,
  33951. 9,
  33952. 9,
  33953. 10,
  33954. 11 // 23: B + 12
  33955. ];
  33956. // uv as integer step (not pixels !)
  33957. var ico_vertexuv = [
  33958. 5, 1, 3, 1, 6, 4, 0, 0,
  33959. 5, 3, 4, 2, 2, 2, 4, 0,
  33960. 2, 0, 1, 1, 6, 0, 6, 2,
  33961. // vertex alias (for same vertex on different faces)
  33962. 0, 4,
  33963. 3, 3,
  33964. 4, 4,
  33965. 3, 1,
  33966. 4, 2,
  33967. 4, 4,
  33968. 0, 2,
  33969. 1, 1,
  33970. 2, 2,
  33971. 3, 3,
  33972. 1, 3,
  33973. 2, 4 // 23: B + 12
  33974. ];
  33975. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33976. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33977. // First island of uv mapping
  33978. // v = 4h 3+ 2
  33979. // v = 3h 9+ 4
  33980. // v = 2h 9+ 5 B
  33981. // v = 1h 9 1 0
  33982. // v = 0h 3 8 7 A
  33983. // u = 0 1 2 3 4 5 6 *a
  33984. // Second island of uv mapping
  33985. // v = 4h 0+ B+ 4+
  33986. // v = 3h A+ 2+
  33987. // v = 2h 7+ 6 3+
  33988. // v = 1h 8+ 3+
  33989. // v = 0h
  33990. // u = 0 1 2 3 4 5 6 *a
  33991. // Face layout on texture UV mapping
  33992. // ============
  33993. // \ 4 /\ 16 / ======
  33994. // \ / \ / /\ 11 /
  33995. // \/ 7 \/ / \ /
  33996. // ======= / 10 \/
  33997. // /\ 17 /\ =======
  33998. // / \ / \ \ 15 /\
  33999. // / 8 \/ 12 \ \ / \
  34000. // ============ \/ 6 \
  34001. // \ 18 /\ ============
  34002. // \ / \ \ 5 /\ 0 /
  34003. // \/ 13 \ \ / \ /
  34004. // ======= \/ 1 \/
  34005. // =============
  34006. // /\ 19 /\ 2 /\
  34007. // / \ / \ / \
  34008. // / 14 \/ 9 \/ 3 \
  34009. // ===================
  34010. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34011. var ustep = 138 / 1024;
  34012. var vstep = 239 / 1024;
  34013. var uoffset = 60 / 1024;
  34014. var voffset = 26 / 1024;
  34015. // Second island should have margin, not to touch the first island
  34016. // avoid any borderline artefact in pixel rounding
  34017. var island_u_offset = -40 / 1024;
  34018. var island_v_offset = +20 / 1024;
  34019. // face is either island 0 or 1 :
  34020. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34021. var island = [
  34022. 0, 0, 0, 0, 1,
  34023. 0, 0, 1, 1, 0,
  34024. 0, 0, 1, 1, 0,
  34025. 0, 1, 1, 1, 0 // 15 - 19
  34026. ];
  34027. var indices = new Array();
  34028. var positions = new Array();
  34029. var normals = new Array();
  34030. var uvs = new Array();
  34031. var current_indice = 0;
  34032. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34033. var face_vertex_pos = new Array(3);
  34034. var face_vertex_uv = new Array(3);
  34035. var v012;
  34036. for (v012 = 0; v012 < 3; v012++) {
  34037. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34038. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34039. }
  34040. // create all with normals
  34041. for (var face = 0; face < 20; face++) {
  34042. // 3 vertex per face
  34043. for (v012 = 0; v012 < 3; v012++) {
  34044. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34045. var v_id = ico_indices[3 * face + v012];
  34046. // vertex have 3D position (x,y,z)
  34047. 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]);
  34048. // Normalize to get normal, then scale to radius
  34049. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34050. // uv Coordinates from vertex ID
  34051. 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);
  34052. }
  34053. // Subdivide the face (interpolate pos, norm, uv)
  34054. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34055. // - norm is linear interpolation of vertex corner normal
  34056. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34057. // - uv is linear interpolation
  34058. //
  34059. // Topology is as below for sub-divide by 2
  34060. // vertex shown as v0,v1,v2
  34061. // interp index is i1 to progress in range [v0,v1[
  34062. // interp index is i2 to progress in range [v0,v2[
  34063. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34064. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34065. //
  34066. //
  34067. // i2 v2
  34068. // ^ ^
  34069. // / / \
  34070. // / / \
  34071. // / / \
  34072. // / / (0,1) \
  34073. // / #---------\
  34074. // / / \ (0,0)'/ \
  34075. // / / \ / \
  34076. // / / \ / \
  34077. // / / (0,0) \ / (1,0) \
  34078. // / #---------#---------\
  34079. // v0 v1
  34080. //
  34081. // --------------------> i1
  34082. //
  34083. // interp of (i1,i2):
  34084. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34085. // along i1 : lerp(x0,x1, i1/(S-i2))
  34086. //
  34087. // centroid of triangle is needed to get help normal computation
  34088. // (c1,c2) are used for centroid location
  34089. var interp_vertex = function (i1, i2, c1, c2) {
  34090. // vertex is interpolated from
  34091. // - face_vertex_pos[0..2]
  34092. // - face_vertex_uv[0..2]
  34093. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34094. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34095. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34096. pos_interp.normalize();
  34097. var vertex_normal;
  34098. if (flat) {
  34099. // in flat mode, recalculate normal as face centroid normal
  34100. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34101. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34102. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34103. }
  34104. else {
  34105. // in smooth mode, recalculate normal from each single vertex position
  34106. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34107. }
  34108. // Vertex normal need correction due to X,Y,Z radius scaling
  34109. vertex_normal.x /= radiusX;
  34110. vertex_normal.y /= radiusY;
  34111. vertex_normal.z /= radiusZ;
  34112. vertex_normal.normalize();
  34113. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34114. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34115. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34116. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34117. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34118. uvs.push(uv_interp.x, uv_interp.y);
  34119. // push each vertex has member of a face
  34120. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34121. indices.push(current_indice);
  34122. current_indice++;
  34123. };
  34124. for (var i2 = 0; i2 < subdivisions; i2++) {
  34125. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34126. // face : (i1,i2) for /\ :
  34127. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34128. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34129. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34130. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34131. if (i1 + i2 + 1 < subdivisions) {
  34132. // face : (i1,i2)' for \/ :
  34133. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34134. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34135. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34136. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34137. }
  34138. }
  34139. }
  34140. }
  34141. // Sides
  34142. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34143. // Result
  34144. var vertexData = new VertexData();
  34145. vertexData.indices = indices;
  34146. vertexData.positions = positions;
  34147. vertexData.normals = normals;
  34148. vertexData.uvs = uvs;
  34149. return vertexData;
  34150. };
  34151. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34152. /**
  34153. * Creates the VertexData of the Polyhedron.
  34154. */
  34155. VertexData.CreatePolyhedron = function (options) {
  34156. // provided polyhedron types :
  34157. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34158. // 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)
  34159. var polyhedra = [];
  34160. 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]] };
  34161. 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]] };
  34162. polyhedra[2] = {
  34163. 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]],
  34164. 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]]
  34165. };
  34166. polyhedra[3] = {
  34167. 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]],
  34168. 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]]
  34169. };
  34170. polyhedra[4] = {
  34171. 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]],
  34172. 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]]
  34173. };
  34174. 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]] };
  34175. 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]] };
  34176. 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]] };
  34177. 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]] };
  34178. 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]] };
  34179. 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]] };
  34180. 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]] };
  34181. 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]] };
  34182. 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]] };
  34183. polyhedra[14] = {
  34184. 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]],
  34185. 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]]
  34186. };
  34187. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34188. var size = options.size;
  34189. var sizeX = options.sizeX || size || 1;
  34190. var sizeY = options.sizeY || size || 1;
  34191. var sizeZ = options.sizeZ || size || 1;
  34192. var data = options.custom || polyhedra[type];
  34193. var nbfaces = data.face.length;
  34194. var faceUV = options.faceUV || new Array(nbfaces);
  34195. var faceColors = options.faceColors;
  34196. var flat = (options.flat === undefined) ? true : options.flat;
  34197. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34198. var positions = new Array();
  34199. var indices = new Array();
  34200. var normals = new Array();
  34201. var uvs = new Array();
  34202. var colors = new Array();
  34203. var index = 0;
  34204. var faceIdx = 0; // face cursor in the array "indexes"
  34205. var indexes = new Array();
  34206. var i = 0;
  34207. var f = 0;
  34208. var u, v, ang, x, y, tmp;
  34209. // default face colors and UV if undefined
  34210. if (flat) {
  34211. for (f = 0; f < nbfaces; f++) {
  34212. if (faceColors && faceColors[f] === undefined) {
  34213. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34214. }
  34215. if (faceUV && faceUV[f] === undefined) {
  34216. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34217. }
  34218. }
  34219. }
  34220. if (!flat) {
  34221. for (i = 0; i < data.vertex.length; i++) {
  34222. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34223. uvs.push(0, 0);
  34224. }
  34225. for (f = 0; f < nbfaces; f++) {
  34226. for (i = 0; i < data.face[f].length - 2; i++) {
  34227. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34228. }
  34229. }
  34230. }
  34231. else {
  34232. for (f = 0; f < nbfaces; f++) {
  34233. var fl = data.face[f].length; // number of vertices of the current face
  34234. ang = 2 * Math.PI / fl;
  34235. x = 0.5 * Math.tan(ang / 2);
  34236. y = 0.5;
  34237. // positions, uvs, colors
  34238. for (i = 0; i < fl; i++) {
  34239. // positions
  34240. 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);
  34241. indexes.push(index);
  34242. index++;
  34243. // uvs
  34244. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34245. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34246. uvs.push(u, v);
  34247. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34248. y = x * Math.sin(ang) + y * Math.cos(ang);
  34249. x = tmp;
  34250. // colors
  34251. if (faceColors) {
  34252. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34253. }
  34254. }
  34255. // indices from indexes
  34256. for (i = 0; i < fl - 2; i++) {
  34257. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34258. }
  34259. faceIdx += fl;
  34260. }
  34261. }
  34262. VertexData.ComputeNormals(positions, indices, normals);
  34263. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34264. var vertexData = new VertexData();
  34265. vertexData.positions = positions;
  34266. vertexData.indices = indices;
  34267. vertexData.normals = normals;
  34268. vertexData.uvs = uvs;
  34269. if (faceColors && flat) {
  34270. vertexData.colors = colors;
  34271. }
  34272. return vertexData;
  34273. };
  34274. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34275. /**
  34276. * Creates the VertexData of the Torus Knot.
  34277. */
  34278. VertexData.CreateTorusKnot = function (options) {
  34279. var indices = new Array();
  34280. var positions = new Array();
  34281. var normals = new Array();
  34282. var uvs = new Array();
  34283. var radius = options.radius || 2;
  34284. var tube = options.tube || 0.5;
  34285. var radialSegments = options.radialSegments || 32;
  34286. var tubularSegments = options.tubularSegments || 32;
  34287. var p = options.p || 2;
  34288. var q = options.q || 3;
  34289. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34290. // Helper
  34291. var getPos = function (angle) {
  34292. var cu = Math.cos(angle);
  34293. var su = Math.sin(angle);
  34294. var quOverP = q / p * angle;
  34295. var cs = Math.cos(quOverP);
  34296. var tx = radius * (2 + cs) * 0.5 * cu;
  34297. var ty = radius * (2 + cs) * su * 0.5;
  34298. var tz = radius * Math.sin(quOverP) * 0.5;
  34299. return new BABYLON.Vector3(tx, ty, tz);
  34300. };
  34301. // Vertices
  34302. var i;
  34303. var j;
  34304. for (i = 0; i <= radialSegments; i++) {
  34305. var modI = i % radialSegments;
  34306. var u = modI / radialSegments * 2 * p * Math.PI;
  34307. var p1 = getPos(u);
  34308. var p2 = getPos(u + 0.01);
  34309. var tang = p2.subtract(p1);
  34310. var n = p2.add(p1);
  34311. var bitan = BABYLON.Vector3.Cross(tang, n);
  34312. n = BABYLON.Vector3.Cross(bitan, tang);
  34313. bitan.normalize();
  34314. n.normalize();
  34315. for (j = 0; j < tubularSegments; j++) {
  34316. var modJ = j % tubularSegments;
  34317. var v = modJ / tubularSegments * 2 * Math.PI;
  34318. var cx = -tube * Math.cos(v);
  34319. var cy = tube * Math.sin(v);
  34320. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34321. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34322. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34323. uvs.push(i / radialSegments);
  34324. uvs.push(j / tubularSegments);
  34325. }
  34326. }
  34327. for (i = 0; i < radialSegments; i++) {
  34328. for (j = 0; j < tubularSegments; j++) {
  34329. var jNext = (j + 1) % tubularSegments;
  34330. var a = i * tubularSegments + j;
  34331. var b = (i + 1) * tubularSegments + j;
  34332. var c = (i + 1) * tubularSegments + jNext;
  34333. var d = i * tubularSegments + jNext;
  34334. indices.push(d);
  34335. indices.push(b);
  34336. indices.push(a);
  34337. indices.push(d);
  34338. indices.push(c);
  34339. indices.push(b);
  34340. }
  34341. }
  34342. // Normals
  34343. VertexData.ComputeNormals(positions, indices, normals);
  34344. // Sides
  34345. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34346. // Result
  34347. var vertexData = new VertexData();
  34348. vertexData.indices = indices;
  34349. vertexData.positions = positions;
  34350. vertexData.normals = normals;
  34351. vertexData.uvs = uvs;
  34352. return vertexData;
  34353. };
  34354. // Tools
  34355. /**
  34356. * @param {any} - positions (number[] or Float32Array)
  34357. * @param {any} - indices (number[] or Uint16Array)
  34358. * @param {any} - normals (number[] or Float32Array)
  34359. * options (optional) :
  34360. * facetPositions : optional array of facet positions (vector3)
  34361. * facetNormals : optional array of facet normals (vector3)
  34362. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34363. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34364. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34365. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34366. * bInfo : optional bounding info, required for facetPartitioning computation
  34367. * useRightHandedSystem: optional boolean to for right handed system computation
  34368. * depthSort : optional boolean to enable the facet depth sort computation
  34369. * distanceTo : optional Vector3 to compute the facet depth from this location
  34370. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34371. */
  34372. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34373. // temporary scalar variables
  34374. var index = 0; // facet index
  34375. var p1p2x = 0.0; // p1p2 vector x coordinate
  34376. var p1p2y = 0.0; // p1p2 vector y coordinate
  34377. var p1p2z = 0.0; // p1p2 vector z coordinate
  34378. var p3p2x = 0.0; // p3p2 vector x coordinate
  34379. var p3p2y = 0.0; // p3p2 vector y coordinate
  34380. var p3p2z = 0.0; // p3p2 vector z coordinate
  34381. var faceNormalx = 0.0; // facet normal x coordinate
  34382. var faceNormaly = 0.0; // facet normal y coordinate
  34383. var faceNormalz = 0.0; // facet normal z coordinate
  34384. var length = 0.0; // facet normal length before normalization
  34385. var v1x = 0; // vector1 x index in the positions array
  34386. var v1y = 0; // vector1 y index in the positions array
  34387. var v1z = 0; // vector1 z index in the positions array
  34388. var v2x = 0; // vector2 x index in the positions array
  34389. var v2y = 0; // vector2 y index in the positions array
  34390. var v2z = 0; // vector2 z index in the positions array
  34391. var v3x = 0; // vector3 x index in the positions array
  34392. var v3y = 0; // vector3 y index in the positions array
  34393. var v3z = 0; // vector3 z index in the positions array
  34394. var computeFacetNormals = false;
  34395. var computeFacetPositions = false;
  34396. var computeFacetPartitioning = false;
  34397. var computeDepthSort = false;
  34398. var faceNormalSign = 1;
  34399. var ratio = 0;
  34400. var distanceTo = null;
  34401. if (options) {
  34402. computeFacetNormals = (options.facetNormals) ? true : false;
  34403. computeFacetPositions = (options.facetPositions) ? true : false;
  34404. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34405. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34406. ratio = options.ratio || 0;
  34407. computeDepthSort = (options.depthSort) ? true : false;
  34408. distanceTo = (options.distanceTo);
  34409. if (computeDepthSort) {
  34410. if (distanceTo === undefined) {
  34411. distanceTo = BABYLON.Vector3.Zero();
  34412. }
  34413. var depthSortedFacets = options.depthSortedFacets;
  34414. }
  34415. }
  34416. // facetPartitioning reinit if needed
  34417. var xSubRatio = 0;
  34418. var ySubRatio = 0;
  34419. var zSubRatio = 0;
  34420. var subSq = 0;
  34421. if (computeFacetPartitioning && options && options.bbSize) {
  34422. var ox = 0; // X partitioning index for facet position
  34423. var oy = 0; // Y partinioning index for facet position
  34424. var oz = 0; // Z partinioning index for facet position
  34425. var b1x = 0; // X partitioning index for facet v1 vertex
  34426. var b1y = 0; // Y partitioning index for facet v1 vertex
  34427. var b1z = 0; // z partitioning index for facet v1 vertex
  34428. var b2x = 0; // X partitioning index for facet v2 vertex
  34429. var b2y = 0; // Y partitioning index for facet v2 vertex
  34430. var b2z = 0; // Z partitioning index for facet v2 vertex
  34431. var b3x = 0; // X partitioning index for facet v3 vertex
  34432. var b3y = 0; // Y partitioning index for facet v3 vertex
  34433. var b3z = 0; // Z partitioning index for facet v3 vertex
  34434. var block_idx_o = 0; // facet barycenter block index
  34435. var block_idx_v1 = 0; // v1 vertex block index
  34436. var block_idx_v2 = 0; // v2 vertex block index
  34437. var block_idx_v3 = 0; // v3 vertex block index
  34438. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34439. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34440. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34441. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34442. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34443. subSq = options.subDiv.max * options.subDiv.max;
  34444. options.facetPartitioning.length = 0;
  34445. }
  34446. // reset the normals
  34447. for (index = 0; index < positions.length; index++) {
  34448. normals[index] = 0.0;
  34449. }
  34450. // Loop : 1 indice triplet = 1 facet
  34451. var nbFaces = (indices.length / 3) | 0;
  34452. for (index = 0; index < nbFaces; index++) {
  34453. // get the indexes of the coordinates of each vertex of the facet
  34454. v1x = indices[index * 3] * 3;
  34455. v1y = v1x + 1;
  34456. v1z = v1x + 2;
  34457. v2x = indices[index * 3 + 1] * 3;
  34458. v2y = v2x + 1;
  34459. v2z = v2x + 2;
  34460. v3x = indices[index * 3 + 2] * 3;
  34461. v3y = v3x + 1;
  34462. v3z = v3x + 2;
  34463. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34464. p1p2y = positions[v1y] - positions[v2y];
  34465. p1p2z = positions[v1z] - positions[v2z];
  34466. p3p2x = positions[v3x] - positions[v2x];
  34467. p3p2y = positions[v3y] - positions[v2y];
  34468. p3p2z = positions[v3z] - positions[v2z];
  34469. // compute the face normal with the cross product
  34470. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34471. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34472. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34473. // normalize this normal and store it in the array facetData
  34474. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34475. length = (length === 0) ? 1.0 : length;
  34476. faceNormalx /= length;
  34477. faceNormaly /= length;
  34478. faceNormalz /= length;
  34479. if (computeFacetNormals && options) {
  34480. options.facetNormals[index].x = faceNormalx;
  34481. options.facetNormals[index].y = faceNormaly;
  34482. options.facetNormals[index].z = faceNormalz;
  34483. }
  34484. if (computeFacetPositions && options) {
  34485. // compute and the facet barycenter coordinates in the array facetPositions
  34486. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34487. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34488. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34489. }
  34490. if (computeFacetPartitioning && options) {
  34491. // store the facet indexes in arrays in the main facetPartitioning array :
  34492. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34493. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34494. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34495. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34496. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34497. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34498. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34499. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34500. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34501. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34502. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34503. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34504. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34505. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34506. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34507. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34508. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34509. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34510. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34511. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34512. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34513. // push each facet index in each block containing the vertex
  34514. options.facetPartitioning[block_idx_v1].push(index);
  34515. if (block_idx_v2 != block_idx_v1) {
  34516. options.facetPartitioning[block_idx_v2].push(index);
  34517. }
  34518. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34519. options.facetPartitioning[block_idx_v3].push(index);
  34520. }
  34521. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34522. options.facetPartitioning[block_idx_o].push(index);
  34523. }
  34524. }
  34525. if (computeDepthSort && options && options.facetPositions) {
  34526. var dsf = depthSortedFacets[index];
  34527. dsf.ind = index * 3;
  34528. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34529. }
  34530. // compute the normals anyway
  34531. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34532. normals[v1y] += faceNormaly;
  34533. normals[v1z] += faceNormalz;
  34534. normals[v2x] += faceNormalx;
  34535. normals[v2y] += faceNormaly;
  34536. normals[v2z] += faceNormalz;
  34537. normals[v3x] += faceNormalx;
  34538. normals[v3y] += faceNormaly;
  34539. normals[v3z] += faceNormalz;
  34540. }
  34541. // last normalization of each normal
  34542. for (index = 0; index < normals.length / 3; index++) {
  34543. faceNormalx = normals[index * 3];
  34544. faceNormaly = normals[index * 3 + 1];
  34545. faceNormalz = normals[index * 3 + 2];
  34546. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34547. length = (length === 0) ? 1.0 : length;
  34548. faceNormalx /= length;
  34549. faceNormaly /= length;
  34550. faceNormalz /= length;
  34551. normals[index * 3] = faceNormalx;
  34552. normals[index * 3 + 1] = faceNormaly;
  34553. normals[index * 3 + 2] = faceNormalz;
  34554. }
  34555. };
  34556. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34557. var li = indices.length;
  34558. var ln = normals.length;
  34559. var i;
  34560. var n;
  34561. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34562. switch (sideOrientation) {
  34563. case BABYLON.Mesh.FRONTSIDE:
  34564. // nothing changed
  34565. break;
  34566. case BABYLON.Mesh.BACKSIDE:
  34567. var tmp;
  34568. // indices
  34569. for (i = 0; i < li; i += 3) {
  34570. tmp = indices[i];
  34571. indices[i] = indices[i + 2];
  34572. indices[i + 2] = tmp;
  34573. }
  34574. // normals
  34575. for (n = 0; n < ln; n++) {
  34576. normals[n] = -normals[n];
  34577. }
  34578. break;
  34579. case BABYLON.Mesh.DOUBLESIDE:
  34580. // positions
  34581. var lp = positions.length;
  34582. var l = lp / 3;
  34583. for (var p = 0; p < lp; p++) {
  34584. positions[lp + p] = positions[p];
  34585. }
  34586. // indices
  34587. for (i = 0; i < li; i += 3) {
  34588. indices[i + li] = indices[i + 2] + l;
  34589. indices[i + 1 + li] = indices[i + 1] + l;
  34590. indices[i + 2 + li] = indices[i] + l;
  34591. }
  34592. // normals
  34593. for (n = 0; n < ln; n++) {
  34594. normals[ln + n] = -normals[n];
  34595. }
  34596. // uvs
  34597. var lu = uvs.length;
  34598. var u = 0;
  34599. for (u = 0; u < lu; u++) {
  34600. uvs[u + lu] = uvs[u];
  34601. }
  34602. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34603. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34604. u = 0;
  34605. for (i = 0; i < lu / 2; i++) {
  34606. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34607. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34608. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34609. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34610. u += 2;
  34611. }
  34612. break;
  34613. }
  34614. };
  34615. /**
  34616. * Creates a new VertexData from the imported parameters.
  34617. */
  34618. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34619. var vertexData = new VertexData();
  34620. // positions
  34621. var positions = parsedVertexData.positions;
  34622. if (positions) {
  34623. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34624. }
  34625. // normals
  34626. var normals = parsedVertexData.normals;
  34627. if (normals) {
  34628. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34629. }
  34630. // tangents
  34631. var tangents = parsedVertexData.tangents;
  34632. if (tangents) {
  34633. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34634. }
  34635. // uvs
  34636. var uvs = parsedVertexData.uvs;
  34637. if (uvs) {
  34638. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34639. }
  34640. // uv2s
  34641. var uv2s = parsedVertexData.uv2s;
  34642. if (uv2s) {
  34643. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34644. }
  34645. // uv3s
  34646. var uv3s = parsedVertexData.uv3s;
  34647. if (uv3s) {
  34648. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34649. }
  34650. // uv4s
  34651. var uv4s = parsedVertexData.uv4s;
  34652. if (uv4s) {
  34653. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34654. }
  34655. // uv5s
  34656. var uv5s = parsedVertexData.uv5s;
  34657. if (uv5s) {
  34658. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34659. }
  34660. // uv6s
  34661. var uv6s = parsedVertexData.uv6s;
  34662. if (uv6s) {
  34663. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34664. }
  34665. // colors
  34666. var colors = parsedVertexData.colors;
  34667. if (colors) {
  34668. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34669. }
  34670. // matricesIndices
  34671. var matricesIndices = parsedVertexData.matricesIndices;
  34672. if (matricesIndices) {
  34673. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34674. }
  34675. // matricesWeights
  34676. var matricesWeights = parsedVertexData.matricesWeights;
  34677. if (matricesWeights) {
  34678. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34679. }
  34680. // indices
  34681. var indices = parsedVertexData.indices;
  34682. if (indices) {
  34683. vertexData.indices = indices;
  34684. }
  34685. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34686. };
  34687. return VertexData;
  34688. }());
  34689. BABYLON.VertexData = VertexData;
  34690. })(BABYLON || (BABYLON = {}));
  34691. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34692. var BABYLON;
  34693. (function (BABYLON) {
  34694. /**
  34695. * Class used to store geometry data (vertex buffers + index buffer)
  34696. */
  34697. var Geometry = /** @class */ (function () {
  34698. /**
  34699. * Creates a new geometry
  34700. * @param id defines the unique ID
  34701. * @param scene defines the hosting scene
  34702. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34703. * @param updatable defines if geometry must be updatable (false by default)
  34704. * @param mesh defines the mesh that will be associated with the geometry
  34705. */
  34706. function Geometry(id, scene, vertexData, updatable, mesh) {
  34707. if (updatable === void 0) { updatable = false; }
  34708. if (mesh === void 0) { mesh = null; }
  34709. /**
  34710. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34711. */
  34712. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34713. this._totalVertices = 0;
  34714. this._isDisposed = false;
  34715. this._indexBufferIsUpdatable = false;
  34716. this.id = id;
  34717. this._engine = scene.getEngine();
  34718. this._meshes = [];
  34719. this._scene = scene;
  34720. //Init vertex buffer cache
  34721. this._vertexBuffers = {};
  34722. this._indices = [];
  34723. this._updatable = updatable;
  34724. // vertexData
  34725. if (vertexData) {
  34726. this.setAllVerticesData(vertexData, updatable);
  34727. }
  34728. else {
  34729. this._totalVertices = 0;
  34730. this._indices = [];
  34731. }
  34732. if (this._engine.getCaps().vertexArrayObject) {
  34733. this._vertexArrayObjects = {};
  34734. }
  34735. // applyToMesh
  34736. if (mesh) {
  34737. if (mesh.getClassName() === "LinesMesh") {
  34738. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34739. this.updateExtend();
  34740. }
  34741. this.applyToMesh(mesh);
  34742. mesh.computeWorldMatrix(true);
  34743. }
  34744. }
  34745. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34746. /**
  34747. * 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
  34748. */
  34749. get: function () {
  34750. return this._boundingBias;
  34751. },
  34752. /**
  34753. * 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
  34754. */
  34755. set: function (value) {
  34756. if (this._boundingBias && this._boundingBias.equals(value)) {
  34757. return;
  34758. }
  34759. this._boundingBias = value.clone();
  34760. this.updateBoundingInfo(true, null);
  34761. },
  34762. enumerable: true,
  34763. configurable: true
  34764. });
  34765. /**
  34766. * Static function used to attach a new empty geometry to a mesh
  34767. * @param mesh defines the mesh to attach the geometry to
  34768. * @returns the new {BABYLON.Geometry}
  34769. */
  34770. Geometry.CreateGeometryForMesh = function (mesh) {
  34771. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34772. geometry.applyToMesh(mesh);
  34773. return geometry;
  34774. };
  34775. Object.defineProperty(Geometry.prototype, "extend", {
  34776. /**
  34777. * Gets the current extend of the geometry
  34778. */
  34779. get: function () {
  34780. return this._extend;
  34781. },
  34782. enumerable: true,
  34783. configurable: true
  34784. });
  34785. /**
  34786. * Gets the hosting scene
  34787. * @returns the hosting {BABYLON.Scene}
  34788. */
  34789. Geometry.prototype.getScene = function () {
  34790. return this._scene;
  34791. };
  34792. /**
  34793. * Gets the hosting engine
  34794. * @returns the hosting {BABYLON.Engine}
  34795. */
  34796. Geometry.prototype.getEngine = function () {
  34797. return this._engine;
  34798. };
  34799. /**
  34800. * Defines if the geometry is ready to use
  34801. * @returns true if the geometry is ready to be used
  34802. */
  34803. Geometry.prototype.isReady = function () {
  34804. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34805. };
  34806. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34807. /**
  34808. * Gets a value indicating that the geometry should not be serialized
  34809. */
  34810. get: function () {
  34811. for (var index = 0; index < this._meshes.length; index++) {
  34812. if (!this._meshes[index].doNotSerialize) {
  34813. return false;
  34814. }
  34815. }
  34816. return true;
  34817. },
  34818. enumerable: true,
  34819. configurable: true
  34820. });
  34821. /** @ignore */
  34822. Geometry.prototype._rebuild = function () {
  34823. if (this._vertexArrayObjects) {
  34824. this._vertexArrayObjects = {};
  34825. }
  34826. // Index buffer
  34827. if (this._meshes.length !== 0 && this._indices) {
  34828. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34829. }
  34830. // Vertex buffers
  34831. for (var key in this._vertexBuffers) {
  34832. var vertexBuffer = this._vertexBuffers[key];
  34833. vertexBuffer._rebuild();
  34834. }
  34835. };
  34836. /**
  34837. * Affects all gemetry data in one call
  34838. * @param vertexData defines the geometry data
  34839. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34840. */
  34841. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34842. vertexData.applyToGeometry(this, updatable);
  34843. this.notifyUpdate();
  34844. };
  34845. /**
  34846. * Set specific vertex data
  34847. * @param kind defines the data kind (Position, normal, etc...)
  34848. * @param data defines the vertex data to use
  34849. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34850. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34851. */
  34852. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34853. if (updatable === void 0) { updatable = false; }
  34854. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34855. this.setVerticesBuffer(buffer);
  34856. };
  34857. /**
  34858. * Removes a specific vertex data
  34859. * @param kind defines the data kind (Position, normal, etc...)
  34860. */
  34861. Geometry.prototype.removeVerticesData = function (kind) {
  34862. if (this._vertexBuffers[kind]) {
  34863. this._vertexBuffers[kind].dispose();
  34864. delete this._vertexBuffers[kind];
  34865. }
  34866. };
  34867. /**
  34868. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34869. * @param buffer defines the vertex buffer to use
  34870. */
  34871. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34872. var kind = buffer.getKind();
  34873. if (this._vertexBuffers[kind]) {
  34874. this._vertexBuffers[kind].dispose();
  34875. }
  34876. this._vertexBuffers[kind] = buffer;
  34877. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34878. var data = buffer.getData();
  34879. var stride = buffer.getStrideSize();
  34880. this._totalVertices = data.length / stride;
  34881. this.updateExtend(data, stride);
  34882. this._resetPointsArrayCache();
  34883. var meshes = this._meshes;
  34884. var numOfMeshes = meshes.length;
  34885. for (var index = 0; index < numOfMeshes; index++) {
  34886. var mesh = meshes[index];
  34887. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34888. mesh._createGlobalSubMesh(false);
  34889. mesh.computeWorldMatrix(true);
  34890. }
  34891. }
  34892. this.notifyUpdate(kind);
  34893. if (this._vertexArrayObjects) {
  34894. this._disposeVertexArrayObjects();
  34895. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34896. }
  34897. };
  34898. /**
  34899. * Update a specific vertex buffer
  34900. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34901. * It will do nothing if the buffer is not updatable
  34902. * @param kind defines the data kind (Position, normal, etc...)
  34903. * @param data defines the data to use
  34904. * @param offset defines the offset in the target buffer where to store the data
  34905. */
  34906. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34907. var vertexBuffer = this.getVertexBuffer(kind);
  34908. if (!vertexBuffer) {
  34909. return;
  34910. }
  34911. vertexBuffer.updateDirectly(data, offset);
  34912. this.notifyUpdate(kind);
  34913. };
  34914. /**
  34915. * Update a specific vertex buffer
  34916. * This function will create a new buffer if the current one is not updatable
  34917. * @param kind defines the data kind (Position, normal, etc...)
  34918. * @param data defines the data to use
  34919. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34920. */
  34921. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34922. if (updateExtends === void 0) { updateExtends = false; }
  34923. var vertexBuffer = this.getVertexBuffer(kind);
  34924. if (!vertexBuffer) {
  34925. return;
  34926. }
  34927. vertexBuffer.update(data);
  34928. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34929. var stride = vertexBuffer.getStrideSize();
  34930. this._totalVertices = data.length / stride;
  34931. this.updateBoundingInfo(updateExtends, data);
  34932. }
  34933. this.notifyUpdate(kind);
  34934. };
  34935. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34936. if (updateExtends) {
  34937. this.updateExtend(data);
  34938. }
  34939. var meshes = this._meshes;
  34940. var numOfMeshes = meshes.length;
  34941. this._resetPointsArrayCache();
  34942. for (var index = 0; index < numOfMeshes; index++) {
  34943. var mesh = meshes[index];
  34944. if (updateExtends) {
  34945. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34946. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34947. var subMesh = mesh.subMeshes[subIndex];
  34948. subMesh.refreshBoundingInfo();
  34949. }
  34950. }
  34951. }
  34952. };
  34953. /** @ignore */
  34954. Geometry.prototype._bind = function (effect, indexToBind) {
  34955. if (!effect) {
  34956. return;
  34957. }
  34958. if (indexToBind === undefined) {
  34959. indexToBind = this._indexBuffer;
  34960. }
  34961. var vbs = this.getVertexBuffers();
  34962. if (!vbs) {
  34963. return;
  34964. }
  34965. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34966. this._engine.bindBuffers(vbs, indexToBind, effect);
  34967. return;
  34968. }
  34969. // Using VAO
  34970. if (!this._vertexArrayObjects[effect.key]) {
  34971. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34972. }
  34973. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34974. };
  34975. /**
  34976. * Gets total number of vertices
  34977. * @returns the total number of vertices
  34978. */
  34979. Geometry.prototype.getTotalVertices = function () {
  34980. if (!this.isReady()) {
  34981. return 0;
  34982. }
  34983. return this._totalVertices;
  34984. };
  34985. /**
  34986. * Gets a specific vertex data attached to this geometry
  34987. * @param kind defines the data kind (Position, normal, etc...)
  34988. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34989. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34990. * @returns a float array containing vertex data
  34991. */
  34992. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34993. var vertexBuffer = this.getVertexBuffer(kind);
  34994. if (!vertexBuffer) {
  34995. return null;
  34996. }
  34997. var orig = vertexBuffer.getData();
  34998. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34999. return orig;
  35000. }
  35001. else {
  35002. var len = orig.length;
  35003. var copy = [];
  35004. for (var i = 0; i < len; i++) {
  35005. copy.push(orig[i]);
  35006. }
  35007. return copy;
  35008. }
  35009. };
  35010. /**
  35011. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35012. * @param kind defines the data kind (Position, normal, etc...)
  35013. * @returns true if the vertex buffer with the specified kind is updatable
  35014. */
  35015. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35016. var vb = this._vertexBuffers[kind];
  35017. if (!vb) {
  35018. return false;
  35019. }
  35020. return vb.isUpdatable();
  35021. };
  35022. /**
  35023. * Gets a specific vertex buffer
  35024. * @param kind defines the data kind (Position, normal, etc...)
  35025. * @returns a {BABYLON.VertexBuffer}
  35026. */
  35027. Geometry.prototype.getVertexBuffer = function (kind) {
  35028. if (!this.isReady()) {
  35029. return null;
  35030. }
  35031. return this._vertexBuffers[kind];
  35032. };
  35033. /**
  35034. * Returns all vertex buffers
  35035. * @return an object holding all vertex buffers indexed by kind
  35036. */
  35037. Geometry.prototype.getVertexBuffers = function () {
  35038. if (!this.isReady()) {
  35039. return null;
  35040. }
  35041. return this._vertexBuffers;
  35042. };
  35043. /**
  35044. * Gets a boolean indicating if specific vertex buffer is present
  35045. * @param kind defines the data kind (Position, normal, etc...)
  35046. * @returns true if data is present
  35047. */
  35048. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35049. if (!this._vertexBuffers) {
  35050. if (this._delayInfo) {
  35051. return this._delayInfo.indexOf(kind) !== -1;
  35052. }
  35053. return false;
  35054. }
  35055. return this._vertexBuffers[kind] !== undefined;
  35056. };
  35057. /**
  35058. * Gets a list of all attached data kinds (Position, normal, etc...)
  35059. * @returns a list of string containing all kinds
  35060. */
  35061. Geometry.prototype.getVerticesDataKinds = function () {
  35062. var result = [];
  35063. var kind;
  35064. if (!this._vertexBuffers && this._delayInfo) {
  35065. for (kind in this._delayInfo) {
  35066. result.push(kind);
  35067. }
  35068. }
  35069. else {
  35070. for (kind in this._vertexBuffers) {
  35071. result.push(kind);
  35072. }
  35073. }
  35074. return result;
  35075. };
  35076. /**
  35077. * Update index buffer
  35078. * @param indices defines the indices to store in the index buffer
  35079. * @param offset defines the offset in the target buffer where to store the data
  35080. */
  35081. Geometry.prototype.updateIndices = function (indices, offset) {
  35082. if (!this._indexBuffer) {
  35083. return;
  35084. }
  35085. if (!this._indexBufferIsUpdatable) {
  35086. this.setIndices(indices, null, true);
  35087. }
  35088. else {
  35089. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35090. }
  35091. };
  35092. /**
  35093. * Creates a new index buffer
  35094. * @param indices defines the indices to store in the index buffer
  35095. * @param totalVertices defines the total number of vertices (could be null)
  35096. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35097. */
  35098. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35099. if (totalVertices === void 0) { totalVertices = null; }
  35100. if (updatable === void 0) { updatable = false; }
  35101. if (this._indexBuffer) {
  35102. this._engine._releaseBuffer(this._indexBuffer);
  35103. }
  35104. this._disposeVertexArrayObjects();
  35105. this._indices = indices;
  35106. this._indexBufferIsUpdatable = updatable;
  35107. if (this._meshes.length !== 0 && this._indices) {
  35108. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35109. }
  35110. if (totalVertices != undefined) {
  35111. this._totalVertices = totalVertices;
  35112. }
  35113. var meshes = this._meshes;
  35114. var numOfMeshes = meshes.length;
  35115. for (var index = 0; index < numOfMeshes; index++) {
  35116. meshes[index]._createGlobalSubMesh(true);
  35117. }
  35118. this.notifyUpdate();
  35119. };
  35120. /**
  35121. * Return the total number of indices
  35122. * @returns the total number of indices
  35123. */
  35124. Geometry.prototype.getTotalIndices = function () {
  35125. if (!this.isReady()) {
  35126. return 0;
  35127. }
  35128. return this._indices.length;
  35129. };
  35130. /**
  35131. * Gets the index buffer array
  35132. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35133. * @returns the index buffer array
  35134. */
  35135. Geometry.prototype.getIndices = function (copyWhenShared) {
  35136. if (!this.isReady()) {
  35137. return null;
  35138. }
  35139. var orig = this._indices;
  35140. if (!copyWhenShared || this._meshes.length === 1) {
  35141. return orig;
  35142. }
  35143. else {
  35144. var len = orig.length;
  35145. var copy = [];
  35146. for (var i = 0; i < len; i++) {
  35147. copy.push(orig[i]);
  35148. }
  35149. return copy;
  35150. }
  35151. };
  35152. /**
  35153. * Gets the index buffer
  35154. * @return the index buffer
  35155. */
  35156. Geometry.prototype.getIndexBuffer = function () {
  35157. if (!this.isReady()) {
  35158. return null;
  35159. }
  35160. return this._indexBuffer;
  35161. };
  35162. /** @ignore */
  35163. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35164. if (effect === void 0) { effect = null; }
  35165. if (!effect || !this._vertexArrayObjects) {
  35166. return;
  35167. }
  35168. if (this._vertexArrayObjects[effect.key]) {
  35169. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35170. delete this._vertexArrayObjects[effect.key];
  35171. }
  35172. };
  35173. /**
  35174. * Release the associated resources for a specific mesh
  35175. * @param mesh defines the source mesh
  35176. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35177. */
  35178. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35179. var meshes = this._meshes;
  35180. var index = meshes.indexOf(mesh);
  35181. if (index === -1) {
  35182. return;
  35183. }
  35184. meshes.splice(index, 1);
  35185. mesh._geometry = null;
  35186. if (meshes.length === 0 && shouldDispose) {
  35187. this.dispose();
  35188. }
  35189. };
  35190. /**
  35191. * Apply current geometry to a given mesh
  35192. * @param mesh defines the mesh to apply geometry to
  35193. */
  35194. Geometry.prototype.applyToMesh = function (mesh) {
  35195. if (mesh._geometry === this) {
  35196. return;
  35197. }
  35198. var previousGeometry = mesh._geometry;
  35199. if (previousGeometry) {
  35200. previousGeometry.releaseForMesh(mesh);
  35201. }
  35202. var meshes = this._meshes;
  35203. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35204. mesh._geometry = this;
  35205. this._scene.pushGeometry(this);
  35206. meshes.push(mesh);
  35207. if (this.isReady()) {
  35208. this._applyToMesh(mesh);
  35209. }
  35210. else {
  35211. mesh._boundingInfo = this._boundingInfo;
  35212. }
  35213. };
  35214. Geometry.prototype.updateExtend = function (data, stride) {
  35215. if (data === void 0) { data = null; }
  35216. if (!data) {
  35217. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35218. }
  35219. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35220. };
  35221. Geometry.prototype._applyToMesh = function (mesh) {
  35222. var numOfMeshes = this._meshes.length;
  35223. // vertexBuffers
  35224. for (var kind in this._vertexBuffers) {
  35225. if (numOfMeshes === 1) {
  35226. this._vertexBuffers[kind].create();
  35227. }
  35228. var buffer = this._vertexBuffers[kind].getBuffer();
  35229. if (buffer)
  35230. buffer.references = numOfMeshes;
  35231. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35232. if (!this._extend) {
  35233. this.updateExtend(this._vertexBuffers[kind].getData());
  35234. }
  35235. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35236. mesh._createGlobalSubMesh(false);
  35237. //bounding info was just created again, world matrix should be applied again.
  35238. mesh._updateBoundingInfo();
  35239. }
  35240. }
  35241. // indexBuffer
  35242. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35243. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35244. }
  35245. if (this._indexBuffer) {
  35246. this._indexBuffer.references = numOfMeshes;
  35247. }
  35248. };
  35249. Geometry.prototype.notifyUpdate = function (kind) {
  35250. if (this.onGeometryUpdated) {
  35251. this.onGeometryUpdated(this, kind);
  35252. }
  35253. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35254. var mesh = _a[_i];
  35255. mesh._markSubMeshesAsAttributesDirty();
  35256. }
  35257. };
  35258. /**
  35259. * Load the geometry if it was flagged as delay loaded
  35260. * @param scene defines the hosting scene
  35261. * @param onLoaded defines a callback called when the geometry is loaded
  35262. */
  35263. Geometry.prototype.load = function (scene, onLoaded) {
  35264. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35265. return;
  35266. }
  35267. if (this.isReady()) {
  35268. if (onLoaded) {
  35269. onLoaded();
  35270. }
  35271. return;
  35272. }
  35273. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35274. this._queueLoad(scene, onLoaded);
  35275. };
  35276. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35277. var _this = this;
  35278. if (!this.delayLoadingFile) {
  35279. return;
  35280. }
  35281. scene._addPendingData(this);
  35282. scene._loadFile(this.delayLoadingFile, function (data) {
  35283. if (!_this._delayLoadingFunction) {
  35284. return;
  35285. }
  35286. _this._delayLoadingFunction(JSON.parse(data), _this);
  35287. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35288. _this._delayInfo = [];
  35289. scene._removePendingData(_this);
  35290. var meshes = _this._meshes;
  35291. var numOfMeshes = meshes.length;
  35292. for (var index = 0; index < numOfMeshes; index++) {
  35293. _this._applyToMesh(meshes[index]);
  35294. }
  35295. if (onLoaded) {
  35296. onLoaded();
  35297. }
  35298. }, undefined, true);
  35299. };
  35300. /**
  35301. * Invert the geometry to move from a right handed system to a left handed one.
  35302. */
  35303. Geometry.prototype.toLeftHanded = function () {
  35304. // Flip faces
  35305. var tIndices = this.getIndices(false);
  35306. if (tIndices != null && tIndices.length > 0) {
  35307. for (var i = 0; i < tIndices.length; i += 3) {
  35308. var tTemp = tIndices[i + 0];
  35309. tIndices[i + 0] = tIndices[i + 2];
  35310. tIndices[i + 2] = tTemp;
  35311. }
  35312. this.setIndices(tIndices);
  35313. }
  35314. // Negate position.z
  35315. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35316. if (tPositions != null && tPositions.length > 0) {
  35317. for (var i = 0; i < tPositions.length; i += 3) {
  35318. tPositions[i + 2] = -tPositions[i + 2];
  35319. }
  35320. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35321. }
  35322. // Negate normal.z
  35323. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35324. if (tNormals != null && tNormals.length > 0) {
  35325. for (var i = 0; i < tNormals.length; i += 3) {
  35326. tNormals[i + 2] = -tNormals[i + 2];
  35327. }
  35328. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35329. }
  35330. };
  35331. // Cache
  35332. /** @ignore */
  35333. Geometry.prototype._resetPointsArrayCache = function () {
  35334. this._positions = null;
  35335. };
  35336. /** @ignore */
  35337. Geometry.prototype._generatePointsArray = function () {
  35338. if (this._positions)
  35339. return true;
  35340. this._positions = [];
  35341. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35342. if (!data) {
  35343. return false;
  35344. }
  35345. for (var index = 0; index < data.length; index += 3) {
  35346. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35347. }
  35348. return true;
  35349. };
  35350. /**
  35351. * Gets a value indicating if the geometry is disposed
  35352. * @returns true if the geometry was disposed
  35353. */
  35354. Geometry.prototype.isDisposed = function () {
  35355. return this._isDisposed;
  35356. };
  35357. Geometry.prototype._disposeVertexArrayObjects = function () {
  35358. if (this._vertexArrayObjects) {
  35359. for (var kind in this._vertexArrayObjects) {
  35360. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35361. }
  35362. this._vertexArrayObjects = {};
  35363. }
  35364. };
  35365. /**
  35366. * Free all associated resources
  35367. */
  35368. Geometry.prototype.dispose = function () {
  35369. var meshes = this._meshes;
  35370. var numOfMeshes = meshes.length;
  35371. var index;
  35372. for (index = 0; index < numOfMeshes; index++) {
  35373. this.releaseForMesh(meshes[index]);
  35374. }
  35375. this._meshes = [];
  35376. this._disposeVertexArrayObjects();
  35377. for (var kind in this._vertexBuffers) {
  35378. this._vertexBuffers[kind].dispose();
  35379. }
  35380. this._vertexBuffers = {};
  35381. this._totalVertices = 0;
  35382. if (this._indexBuffer) {
  35383. this._engine._releaseBuffer(this._indexBuffer);
  35384. }
  35385. this._indexBuffer = null;
  35386. this._indices = [];
  35387. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35388. this.delayLoadingFile = null;
  35389. this._delayLoadingFunction = null;
  35390. this._delayInfo = [];
  35391. this._boundingInfo = null;
  35392. this._scene.removeGeometry(this);
  35393. this._isDisposed = true;
  35394. };
  35395. /**
  35396. * Clone the current geometry into a new geometry
  35397. * @param id defines the unique ID of the new geometry
  35398. * @returns a new geometry object
  35399. */
  35400. Geometry.prototype.copy = function (id) {
  35401. var vertexData = new BABYLON.VertexData();
  35402. vertexData.indices = [];
  35403. var indices = this.getIndices();
  35404. if (indices) {
  35405. for (var index = 0; index < indices.length; index++) {
  35406. vertexData.indices.push(indices[index]);
  35407. }
  35408. }
  35409. var updatable = false;
  35410. var stopChecking = false;
  35411. var kind;
  35412. for (kind in this._vertexBuffers) {
  35413. // using slice() to make a copy of the array and not just reference it
  35414. var data = this.getVerticesData(kind);
  35415. if (data instanceof Float32Array) {
  35416. vertexData.set(new Float32Array(data), kind);
  35417. }
  35418. else {
  35419. vertexData.set(data.slice(0), kind);
  35420. }
  35421. if (!stopChecking) {
  35422. var vb = this.getVertexBuffer(kind);
  35423. if (vb) {
  35424. updatable = vb.isUpdatable();
  35425. stopChecking = !updatable;
  35426. }
  35427. }
  35428. }
  35429. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35430. geometry.delayLoadState = this.delayLoadState;
  35431. geometry.delayLoadingFile = this.delayLoadingFile;
  35432. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35433. for (kind in this._delayInfo) {
  35434. geometry._delayInfo = geometry._delayInfo || [];
  35435. geometry._delayInfo.push(kind);
  35436. }
  35437. // Bounding info
  35438. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35439. return geometry;
  35440. };
  35441. /**
  35442. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35443. * @return a JSON representation of the current geometry data (without the vertices data)
  35444. */
  35445. Geometry.prototype.serialize = function () {
  35446. var serializationObject = {};
  35447. serializationObject.id = this.id;
  35448. serializationObject.updatable = this._updatable;
  35449. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35450. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35451. }
  35452. return serializationObject;
  35453. };
  35454. Geometry.prototype.toNumberArray = function (origin) {
  35455. if (Array.isArray(origin)) {
  35456. return origin;
  35457. }
  35458. else {
  35459. return Array.prototype.slice.call(origin);
  35460. }
  35461. };
  35462. /**
  35463. * Serialize all vertices data into a JSON oject
  35464. * @returns a JSON representation of the current geometry data
  35465. */
  35466. Geometry.prototype.serializeVerticeData = function () {
  35467. var serializationObject = this.serialize();
  35468. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35469. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35470. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35471. serializationObject.positions._updatable = true;
  35472. }
  35473. }
  35474. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35475. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35476. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35477. serializationObject.normals._updatable = true;
  35478. }
  35479. }
  35480. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35481. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35482. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35483. serializationObject.tangets._updatable = true;
  35484. }
  35485. }
  35486. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35487. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35488. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35489. serializationObject.uvs._updatable = true;
  35490. }
  35491. }
  35492. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35493. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35494. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35495. serializationObject.uv2s._updatable = true;
  35496. }
  35497. }
  35498. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35499. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35500. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35501. serializationObject.uv3s._updatable = true;
  35502. }
  35503. }
  35504. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35505. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35506. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35507. serializationObject.uv4s._updatable = true;
  35508. }
  35509. }
  35510. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35511. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35512. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35513. serializationObject.uv5s._updatable = true;
  35514. }
  35515. }
  35516. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35517. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35518. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35519. serializationObject.uv6s._updatable = true;
  35520. }
  35521. }
  35522. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35523. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35524. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35525. serializationObject.colors._updatable = true;
  35526. }
  35527. }
  35528. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35529. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35530. serializationObject.matricesIndices._isExpanded = true;
  35531. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35532. serializationObject.matricesIndices._updatable = true;
  35533. }
  35534. }
  35535. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35536. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35537. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35538. serializationObject.matricesWeights._updatable = true;
  35539. }
  35540. }
  35541. serializationObject.indices = this.toNumberArray(this.getIndices());
  35542. return serializationObject;
  35543. };
  35544. // Statics
  35545. /**
  35546. * Extracts a clone of a mesh geometry
  35547. * @param mesh defines the source mesh
  35548. * @param id defines the unique ID of the new geometry object
  35549. * @returns the new geometry object
  35550. */
  35551. Geometry.ExtractFromMesh = function (mesh, id) {
  35552. var geometry = mesh._geometry;
  35553. if (!geometry) {
  35554. return null;
  35555. }
  35556. return geometry.copy(id);
  35557. };
  35558. /**
  35559. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35560. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35561. * Be aware Math.random() could cause collisions, but:
  35562. * "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"
  35563. * @returns a string containing a new GUID
  35564. */
  35565. Geometry.RandomId = function () {
  35566. return BABYLON.Tools.RandomId();
  35567. };
  35568. /** @ignore */
  35569. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35570. var scene = mesh.getScene();
  35571. // Geometry
  35572. var geometryId = parsedGeometry.geometryId;
  35573. if (geometryId) {
  35574. var geometry = scene.getGeometryByID(geometryId);
  35575. if (geometry) {
  35576. geometry.applyToMesh(mesh);
  35577. }
  35578. }
  35579. else if (parsedGeometry instanceof ArrayBuffer) {
  35580. var binaryInfo = mesh._binaryInfo;
  35581. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35582. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35583. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35584. }
  35585. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35586. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35587. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35588. }
  35589. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35590. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35591. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35592. }
  35593. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35594. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35595. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35596. }
  35597. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35598. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35599. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35600. }
  35601. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35602. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35603. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35604. }
  35605. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35606. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35607. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35608. }
  35609. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35610. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35611. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35612. }
  35613. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35614. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35615. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35616. }
  35617. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35618. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35619. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35620. }
  35621. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35622. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35623. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35624. }
  35625. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35626. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35627. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35628. }
  35629. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35630. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35631. mesh.setIndices(indicesData, null);
  35632. }
  35633. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35634. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35635. mesh.subMeshes = [];
  35636. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35637. var materialIndex = subMeshesData[(i * 5) + 0];
  35638. var verticesStart = subMeshesData[(i * 5) + 1];
  35639. var verticesCount = subMeshesData[(i * 5) + 2];
  35640. var indexStart = subMeshesData[(i * 5) + 3];
  35641. var indexCount = subMeshesData[(i * 5) + 4];
  35642. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35643. }
  35644. }
  35645. }
  35646. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35647. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35648. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35649. if (parsedGeometry.tangents) {
  35650. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35651. }
  35652. if (parsedGeometry.uvs) {
  35653. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35654. }
  35655. if (parsedGeometry.uvs2) {
  35656. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35657. }
  35658. if (parsedGeometry.uvs3) {
  35659. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35660. }
  35661. if (parsedGeometry.uvs4) {
  35662. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35663. }
  35664. if (parsedGeometry.uvs5) {
  35665. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35666. }
  35667. if (parsedGeometry.uvs6) {
  35668. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35669. }
  35670. if (parsedGeometry.colors) {
  35671. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35672. }
  35673. if (parsedGeometry.matricesIndices) {
  35674. if (!parsedGeometry.matricesIndices._isExpanded) {
  35675. var floatIndices = [];
  35676. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35677. var matricesIndex = parsedGeometry.matricesIndices[i];
  35678. floatIndices.push(matricesIndex & 0x000000FF);
  35679. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35680. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35681. floatIndices.push(matricesIndex >> 24);
  35682. }
  35683. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35684. }
  35685. else {
  35686. delete parsedGeometry.matricesIndices._isExpanded;
  35687. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35688. }
  35689. }
  35690. if (parsedGeometry.matricesIndicesExtra) {
  35691. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35692. var floatIndices = [];
  35693. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35694. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35695. floatIndices.push(matricesIndex & 0x000000FF);
  35696. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35697. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35698. floatIndices.push(matricesIndex >> 24);
  35699. }
  35700. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35701. }
  35702. else {
  35703. delete parsedGeometry.matricesIndices._isExpanded;
  35704. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35705. }
  35706. }
  35707. if (parsedGeometry.matricesWeights) {
  35708. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35709. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35710. }
  35711. if (parsedGeometry.matricesWeightsExtra) {
  35712. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35713. }
  35714. mesh.setIndices(parsedGeometry.indices, null);
  35715. }
  35716. // SubMeshes
  35717. if (parsedGeometry.subMeshes) {
  35718. mesh.subMeshes = [];
  35719. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35720. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35721. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35722. }
  35723. }
  35724. // Flat shading
  35725. if (mesh._shouldGenerateFlatShading) {
  35726. mesh.convertToFlatShadedMesh();
  35727. delete mesh._shouldGenerateFlatShading;
  35728. }
  35729. // Update
  35730. mesh.computeWorldMatrix(true);
  35731. // Octree
  35732. var sceneOctree = scene.selectionOctree;
  35733. if (sceneOctree !== undefined && sceneOctree !== null) {
  35734. sceneOctree.addMesh(mesh);
  35735. }
  35736. };
  35737. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35738. var epsilon = 1e-3;
  35739. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35740. return;
  35741. }
  35742. var noInfluenceBoneIndex = 0.0;
  35743. if (parsedGeometry.skeletonId > -1) {
  35744. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35745. if (!skeleton) {
  35746. return;
  35747. }
  35748. noInfluenceBoneIndex = skeleton.bones.length;
  35749. }
  35750. else {
  35751. return;
  35752. }
  35753. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35754. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35755. var matricesWeights = parsedGeometry.matricesWeights;
  35756. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35757. var influencers = parsedGeometry.numBoneInfluencer;
  35758. var size = matricesWeights.length;
  35759. for (var i = 0; i < size; i += 4) {
  35760. var weight = 0.0;
  35761. var firstZeroWeight = -1;
  35762. for (var j = 0; j < 4; j++) {
  35763. var w = matricesWeights[i + j];
  35764. weight += w;
  35765. if (w < epsilon && firstZeroWeight < 0) {
  35766. firstZeroWeight = j;
  35767. }
  35768. }
  35769. if (matricesWeightsExtra) {
  35770. for (var j = 0; j < 4; j++) {
  35771. var w = matricesWeightsExtra[i + j];
  35772. weight += w;
  35773. if (w < epsilon && firstZeroWeight < 0) {
  35774. firstZeroWeight = j + 4;
  35775. }
  35776. }
  35777. }
  35778. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35779. firstZeroWeight = influencers - 1;
  35780. }
  35781. if (weight > epsilon) {
  35782. var mweight = 1.0 / weight;
  35783. for (var j = 0; j < 4; j++) {
  35784. matricesWeights[i + j] *= mweight;
  35785. }
  35786. if (matricesWeightsExtra) {
  35787. for (var j = 0; j < 4; j++) {
  35788. matricesWeightsExtra[i + j] *= mweight;
  35789. }
  35790. }
  35791. }
  35792. else {
  35793. if (firstZeroWeight >= 4) {
  35794. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35795. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35796. }
  35797. else {
  35798. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35799. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35800. }
  35801. }
  35802. }
  35803. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35804. if (parsedGeometry.matricesWeightsExtra) {
  35805. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35806. }
  35807. };
  35808. /**
  35809. * Create a new geometry from persisted data (Using .babylon file format)
  35810. * @param parsedVertexData defines the persisted data
  35811. * @param scene defines the hosting scene
  35812. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35813. * @returns the new geometry object
  35814. */
  35815. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35816. if (scene.getGeometryByID(parsedVertexData.id)) {
  35817. return null; // null since geometry could be something else than a box...
  35818. }
  35819. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35820. if (BABYLON.Tags) {
  35821. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35822. }
  35823. if (parsedVertexData.delayLoadingFile) {
  35824. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35825. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35826. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35827. geometry._delayInfo = [];
  35828. if (parsedVertexData.hasUVs) {
  35829. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35830. }
  35831. if (parsedVertexData.hasUVs2) {
  35832. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35833. }
  35834. if (parsedVertexData.hasUVs3) {
  35835. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35836. }
  35837. if (parsedVertexData.hasUVs4) {
  35838. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35839. }
  35840. if (parsedVertexData.hasUVs5) {
  35841. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35842. }
  35843. if (parsedVertexData.hasUVs6) {
  35844. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35845. }
  35846. if (parsedVertexData.hasColors) {
  35847. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35848. }
  35849. if (parsedVertexData.hasMatricesIndices) {
  35850. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35851. }
  35852. if (parsedVertexData.hasMatricesWeights) {
  35853. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35854. }
  35855. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35856. }
  35857. else {
  35858. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35859. }
  35860. scene.pushGeometry(geometry, true);
  35861. return geometry;
  35862. };
  35863. return Geometry;
  35864. }());
  35865. BABYLON.Geometry = Geometry;
  35866. // Primitives
  35867. /// Abstract class
  35868. /**
  35869. * Abstract class used to provide common services for all typed geometries
  35870. */
  35871. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35872. __extends(_PrimitiveGeometry, _super);
  35873. /**
  35874. * Creates a new typed geometry
  35875. * @param id defines the unique ID of the geometry
  35876. * @param scene defines the hosting scene
  35877. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35878. * @param mesh defines the hosting mesh (can be null)
  35879. */
  35880. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35881. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35882. if (mesh === void 0) { mesh = null; }
  35883. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35884. _this._canBeRegenerated = _canBeRegenerated;
  35885. _this._beingRegenerated = true;
  35886. _this.regenerate();
  35887. _this._beingRegenerated = false;
  35888. return _this;
  35889. }
  35890. /**
  35891. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35892. * @returns true if the geometry can be regenerated
  35893. */
  35894. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35895. return this._canBeRegenerated;
  35896. };
  35897. /**
  35898. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35899. */
  35900. _PrimitiveGeometry.prototype.regenerate = function () {
  35901. if (!this._canBeRegenerated) {
  35902. return;
  35903. }
  35904. this._beingRegenerated = true;
  35905. this.setAllVerticesData(this._regenerateVertexData(), false);
  35906. this._beingRegenerated = false;
  35907. };
  35908. /**
  35909. * Clone the geometry
  35910. * @param id defines the unique ID of the new geometry
  35911. * @returns the new geometry
  35912. */
  35913. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35914. return _super.prototype.copy.call(this, id);
  35915. };
  35916. // overrides
  35917. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35918. if (!this._beingRegenerated) {
  35919. return;
  35920. }
  35921. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35922. };
  35923. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35924. if (!this._beingRegenerated) {
  35925. return;
  35926. }
  35927. _super.prototype.setVerticesData.call(this, kind, data, false);
  35928. };
  35929. // to override
  35930. /** @ignore */
  35931. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35932. throw new Error("Abstract method");
  35933. };
  35934. _PrimitiveGeometry.prototype.copy = function (id) {
  35935. throw new Error("Must be overriden in sub-classes.");
  35936. };
  35937. _PrimitiveGeometry.prototype.serialize = function () {
  35938. var serializationObject = _super.prototype.serialize.call(this);
  35939. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35940. return serializationObject;
  35941. };
  35942. return _PrimitiveGeometry;
  35943. }(Geometry));
  35944. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35945. /**
  35946. * Creates a ribbon geometry
  35947. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35948. */
  35949. var RibbonGeometry = /** @class */ (function (_super) {
  35950. __extends(RibbonGeometry, _super);
  35951. /**
  35952. * Creates a ribbon geometry
  35953. * @param id defines the unique ID of the geometry
  35954. * @param scene defines the hosting scene
  35955. * @param pathArray defines the array of paths to use
  35956. * @param closeArray defines if the last path and the first path must be joined
  35957. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35958. * @param offset defines the offset between points
  35959. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35960. * @param mesh defines the hosting mesh (can be null)
  35961. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35962. */
  35963. function RibbonGeometry(id, scene,
  35964. /**
  35965. * Defines the array of paths to use
  35966. */
  35967. pathArray,
  35968. /**
  35969. * Defines if the last and first points of each path in your pathArray must be joined
  35970. */
  35971. closeArray,
  35972. /**
  35973. * Defines if the last and first points of each path in your pathArray must be joined
  35974. */
  35975. closePath,
  35976. /**
  35977. * Defines the offset between points
  35978. */
  35979. offset, canBeRegenerated, mesh,
  35980. /**
  35981. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35982. */
  35983. side) {
  35984. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35985. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35986. _this.pathArray = pathArray;
  35987. _this.closeArray = closeArray;
  35988. _this.closePath = closePath;
  35989. _this.offset = offset;
  35990. _this.side = side;
  35991. return _this;
  35992. }
  35993. /** @ignore */
  35994. RibbonGeometry.prototype._regenerateVertexData = function () {
  35995. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35996. };
  35997. RibbonGeometry.prototype.copy = function (id) {
  35998. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35999. };
  36000. return RibbonGeometry;
  36001. }(_PrimitiveGeometry));
  36002. BABYLON.RibbonGeometry = RibbonGeometry;
  36003. /**
  36004. * Creates a box geometry
  36005. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36006. */
  36007. var BoxGeometry = /** @class */ (function (_super) {
  36008. __extends(BoxGeometry, _super);
  36009. /**
  36010. * Creates a box geometry
  36011. * @param id defines the unique ID of the geometry
  36012. * @param scene defines the hosting scene
  36013. * @param size defines the zise of the box (width, height and depth are the same)
  36014. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36015. * @param mesh defines the hosting mesh (can be null)
  36016. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36017. */
  36018. function BoxGeometry(id, scene,
  36019. /**
  36020. * Defines the zise of the box (width, height and depth are the same)
  36021. */
  36022. size, canBeRegenerated, mesh,
  36023. /**
  36024. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36025. */
  36026. side) {
  36027. if (mesh === void 0) { mesh = null; }
  36028. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36029. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36030. _this.size = size;
  36031. _this.side = side;
  36032. return _this;
  36033. }
  36034. BoxGeometry.prototype._regenerateVertexData = function () {
  36035. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36036. };
  36037. BoxGeometry.prototype.copy = function (id) {
  36038. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36039. };
  36040. BoxGeometry.prototype.serialize = function () {
  36041. var serializationObject = _super.prototype.serialize.call(this);
  36042. serializationObject.size = this.size;
  36043. return serializationObject;
  36044. };
  36045. BoxGeometry.Parse = function (parsedBox, scene) {
  36046. if (scene.getGeometryByID(parsedBox.id)) {
  36047. return null; // null since geometry could be something else than a box...
  36048. }
  36049. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36050. if (BABYLON.Tags) {
  36051. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36052. }
  36053. scene.pushGeometry(box, true);
  36054. return box;
  36055. };
  36056. return BoxGeometry;
  36057. }(_PrimitiveGeometry));
  36058. BABYLON.BoxGeometry = BoxGeometry;
  36059. /**
  36060. * Creates a sphere geometry
  36061. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36062. */
  36063. var SphereGeometry = /** @class */ (function (_super) {
  36064. __extends(SphereGeometry, _super);
  36065. /**
  36066. * Create a new sphere geometry
  36067. * @param id defines the unique ID of the geometry
  36068. * @param scene defines the hosting scene
  36069. * @param segments defines the number of segments to use to create the sphere
  36070. * @param diameter defines the diameter of the sphere
  36071. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36072. * @param mesh defines the hosting mesh (can be null)
  36073. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36074. */
  36075. function SphereGeometry(id, scene,
  36076. /**
  36077. * Defines the number of segments to use to create the sphere
  36078. */
  36079. segments,
  36080. /**
  36081. * Defines the diameter of the sphere
  36082. */
  36083. diameter, canBeRegenerated, mesh,
  36084. /**
  36085. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36086. */
  36087. side) {
  36088. if (mesh === void 0) { mesh = null; }
  36089. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36090. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36091. _this.segments = segments;
  36092. _this.diameter = diameter;
  36093. _this.side = side;
  36094. return _this;
  36095. }
  36096. SphereGeometry.prototype._regenerateVertexData = function () {
  36097. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36098. };
  36099. SphereGeometry.prototype.copy = function (id) {
  36100. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36101. };
  36102. SphereGeometry.prototype.serialize = function () {
  36103. var serializationObject = _super.prototype.serialize.call(this);
  36104. serializationObject.segments = this.segments;
  36105. serializationObject.diameter = this.diameter;
  36106. return serializationObject;
  36107. };
  36108. SphereGeometry.Parse = function (parsedSphere, scene) {
  36109. if (scene.getGeometryByID(parsedSphere.id)) {
  36110. return null; // null since geometry could be something else than a sphere...
  36111. }
  36112. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36113. if (BABYLON.Tags) {
  36114. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36115. }
  36116. scene.pushGeometry(sphere, true);
  36117. return sphere;
  36118. };
  36119. return SphereGeometry;
  36120. }(_PrimitiveGeometry));
  36121. BABYLON.SphereGeometry = SphereGeometry;
  36122. /**
  36123. * Creates a disc geometry
  36124. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36125. */
  36126. var DiscGeometry = /** @class */ (function (_super) {
  36127. __extends(DiscGeometry, _super);
  36128. /**
  36129. * Creates a new disc geometry
  36130. * @param id defines the unique ID of the geometry
  36131. * @param scene defines the hosting scene
  36132. * @param radius defines the radius of the disc
  36133. * @param tessellation defines the tesselation factor to apply to the disc
  36134. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36135. * @param mesh defines the hosting mesh (can be null)
  36136. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36137. */
  36138. function DiscGeometry(id, scene,
  36139. /**
  36140. * Defines the radius of the disc
  36141. */
  36142. radius,
  36143. /**
  36144. * Defines the tesselation factor to apply to the disc
  36145. */
  36146. tessellation, canBeRegenerated, mesh,
  36147. /**
  36148. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36149. */
  36150. side) {
  36151. if (mesh === void 0) { mesh = null; }
  36152. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36153. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36154. _this.radius = radius;
  36155. _this.tessellation = tessellation;
  36156. _this.side = side;
  36157. return _this;
  36158. }
  36159. DiscGeometry.prototype._regenerateVertexData = function () {
  36160. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36161. };
  36162. DiscGeometry.prototype.copy = function (id) {
  36163. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36164. };
  36165. return DiscGeometry;
  36166. }(_PrimitiveGeometry));
  36167. BABYLON.DiscGeometry = DiscGeometry;
  36168. /**
  36169. * Creates a new cylinder geometry
  36170. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36171. */
  36172. var CylinderGeometry = /** @class */ (function (_super) {
  36173. __extends(CylinderGeometry, _super);
  36174. /**
  36175. * Creates a new cylinder geometry
  36176. * @param id defines the unique ID of the geometry
  36177. * @param scene defines the hosting scene
  36178. * @param height defines the height of the cylinder
  36179. * @param diameterTop defines the diameter of the cylinder's top cap
  36180. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36181. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36182. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36183. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36184. * @param mesh defines the hosting mesh (can be null)
  36185. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36186. */
  36187. function CylinderGeometry(id, scene,
  36188. /**
  36189. * Defines the height of the cylinder
  36190. */
  36191. height,
  36192. /**
  36193. * Defines the diameter of the cylinder's top cap
  36194. */
  36195. diameterTop,
  36196. /**
  36197. * Defines the diameter of the cylinder's bottom cap
  36198. */
  36199. diameterBottom,
  36200. /**
  36201. * Defines the tessellation factor to apply to the cylinder
  36202. */
  36203. tessellation,
  36204. /**
  36205. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36206. */
  36207. subdivisions, canBeRegenerated, mesh,
  36208. /**
  36209. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36210. */
  36211. side) {
  36212. if (subdivisions === void 0) { subdivisions = 1; }
  36213. if (mesh === void 0) { mesh = null; }
  36214. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36215. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36216. _this.height = height;
  36217. _this.diameterTop = diameterTop;
  36218. _this.diameterBottom = diameterBottom;
  36219. _this.tessellation = tessellation;
  36220. _this.subdivisions = subdivisions;
  36221. _this.side = side;
  36222. return _this;
  36223. }
  36224. CylinderGeometry.prototype._regenerateVertexData = function () {
  36225. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36226. };
  36227. CylinderGeometry.prototype.copy = function (id) {
  36228. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36229. };
  36230. CylinderGeometry.prototype.serialize = function () {
  36231. var serializationObject = _super.prototype.serialize.call(this);
  36232. serializationObject.height = this.height;
  36233. serializationObject.diameterTop = this.diameterTop;
  36234. serializationObject.diameterBottom = this.diameterBottom;
  36235. serializationObject.tessellation = this.tessellation;
  36236. return serializationObject;
  36237. };
  36238. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36239. if (scene.getGeometryByID(parsedCylinder.id)) {
  36240. return null; // null since geometry could be something else than a cylinder...
  36241. }
  36242. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36243. if (BABYLON.Tags) {
  36244. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36245. }
  36246. scene.pushGeometry(cylinder, true);
  36247. return cylinder;
  36248. };
  36249. return CylinderGeometry;
  36250. }(_PrimitiveGeometry));
  36251. BABYLON.CylinderGeometry = CylinderGeometry;
  36252. /**
  36253. * Creates a new torus geometry
  36254. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36255. */
  36256. var TorusGeometry = /** @class */ (function (_super) {
  36257. __extends(TorusGeometry, _super);
  36258. /**
  36259. * Creates a new torus geometry
  36260. * @param id defines the unique ID of the geometry
  36261. * @param scene defines the hosting scene
  36262. * @param diameter defines the diameter of the torus
  36263. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36264. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36265. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36266. * @param mesh defines the hosting mesh (can be null)
  36267. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36268. */
  36269. function TorusGeometry(id, scene,
  36270. /**
  36271. * Defines the diameter of the torus
  36272. */
  36273. diameter,
  36274. /**
  36275. * Defines the thickness of the torus (ie. internal diameter)
  36276. */
  36277. thickness,
  36278. /**
  36279. * Defines the tesselation factor to apply to the torus
  36280. */
  36281. tessellation, canBeRegenerated, mesh,
  36282. /**
  36283. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36284. */
  36285. side) {
  36286. if (mesh === void 0) { mesh = null; }
  36287. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36288. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36289. _this.diameter = diameter;
  36290. _this.thickness = thickness;
  36291. _this.tessellation = tessellation;
  36292. _this.side = side;
  36293. return _this;
  36294. }
  36295. TorusGeometry.prototype._regenerateVertexData = function () {
  36296. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36297. };
  36298. TorusGeometry.prototype.copy = function (id) {
  36299. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36300. };
  36301. TorusGeometry.prototype.serialize = function () {
  36302. var serializationObject = _super.prototype.serialize.call(this);
  36303. serializationObject.diameter = this.diameter;
  36304. serializationObject.thickness = this.thickness;
  36305. serializationObject.tessellation = this.tessellation;
  36306. return serializationObject;
  36307. };
  36308. TorusGeometry.Parse = function (parsedTorus, scene) {
  36309. if (scene.getGeometryByID(parsedTorus.id)) {
  36310. return null; // null since geometry could be something else than a torus...
  36311. }
  36312. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36313. if (BABYLON.Tags) {
  36314. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36315. }
  36316. scene.pushGeometry(torus, true);
  36317. return torus;
  36318. };
  36319. return TorusGeometry;
  36320. }(_PrimitiveGeometry));
  36321. BABYLON.TorusGeometry = TorusGeometry;
  36322. /**
  36323. * Creates a new ground geometry
  36324. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36325. */
  36326. var GroundGeometry = /** @class */ (function (_super) {
  36327. __extends(GroundGeometry, _super);
  36328. /**
  36329. * Creates a new ground geometry
  36330. * @param id defines the unique ID of the geometry
  36331. * @param scene defines the hosting scene
  36332. * @param width defines the width of the ground
  36333. * @param height defines the height of the ground
  36334. * @param subdivisions defines the subdivisions to apply to the ground
  36335. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36336. * @param mesh defines the hosting mesh (can be null)
  36337. */
  36338. function GroundGeometry(id, scene,
  36339. /**
  36340. * Defines the width of the ground
  36341. */
  36342. width,
  36343. /**
  36344. * Defines the height of the ground
  36345. */
  36346. height,
  36347. /**
  36348. * Defines the subdivisions to apply to the ground
  36349. */
  36350. subdivisions, canBeRegenerated, mesh) {
  36351. if (mesh === void 0) { mesh = null; }
  36352. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36353. _this.width = width;
  36354. _this.height = height;
  36355. _this.subdivisions = subdivisions;
  36356. return _this;
  36357. }
  36358. GroundGeometry.prototype._regenerateVertexData = function () {
  36359. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36360. };
  36361. GroundGeometry.prototype.copy = function (id) {
  36362. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36363. };
  36364. GroundGeometry.prototype.serialize = function () {
  36365. var serializationObject = _super.prototype.serialize.call(this);
  36366. serializationObject.width = this.width;
  36367. serializationObject.height = this.height;
  36368. serializationObject.subdivisions = this.subdivisions;
  36369. return serializationObject;
  36370. };
  36371. GroundGeometry.Parse = function (parsedGround, scene) {
  36372. if (scene.getGeometryByID(parsedGround.id)) {
  36373. return null; // null since geometry could be something else than a ground...
  36374. }
  36375. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36376. if (BABYLON.Tags) {
  36377. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36378. }
  36379. scene.pushGeometry(ground, true);
  36380. return ground;
  36381. };
  36382. return GroundGeometry;
  36383. }(_PrimitiveGeometry));
  36384. BABYLON.GroundGeometry = GroundGeometry;
  36385. /**
  36386. * Creates a tiled ground geometry
  36387. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36388. */
  36389. var TiledGroundGeometry = /** @class */ (function (_super) {
  36390. __extends(TiledGroundGeometry, _super);
  36391. /**
  36392. * Creates a tiled ground geometry
  36393. * @param id defines the unique ID of the geometry
  36394. * @param scene defines the hosting scene
  36395. * @param xmin defines the minimum value on X axis
  36396. * @param zmin defines the minimum value on Z axis
  36397. * @param xmax defines the maximum value on X axis
  36398. * @param zmax defines the maximum value on Z axis
  36399. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36400. * @param precision defines the precision to use when computing the tiles
  36401. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36402. * @param mesh defines the hosting mesh (can be null)
  36403. */
  36404. function TiledGroundGeometry(id, scene,
  36405. /**
  36406. * Defines the minimum value on X axis
  36407. */
  36408. xmin,
  36409. /**
  36410. * Defines the minimum value on Z axis
  36411. */
  36412. zmin,
  36413. /**
  36414. * Defines the maximum value on X axis
  36415. */
  36416. xmax,
  36417. /**
  36418. * Defines the maximum value on Z axis
  36419. */
  36420. zmax,
  36421. /**
  36422. * Defines the subdivisions to apply to the ground
  36423. */
  36424. subdivisions,
  36425. /**
  36426. * Defines the precision to use when computing the tiles
  36427. */
  36428. precision, canBeRegenerated, mesh) {
  36429. if (mesh === void 0) { mesh = null; }
  36430. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36431. _this.xmin = xmin;
  36432. _this.zmin = zmin;
  36433. _this.xmax = xmax;
  36434. _this.zmax = zmax;
  36435. _this.subdivisions = subdivisions;
  36436. _this.precision = precision;
  36437. return _this;
  36438. }
  36439. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36440. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36441. };
  36442. TiledGroundGeometry.prototype.copy = function (id) {
  36443. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36444. };
  36445. return TiledGroundGeometry;
  36446. }(_PrimitiveGeometry));
  36447. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36448. /**
  36449. * Creates a plane geometry
  36450. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36451. */
  36452. var PlaneGeometry = /** @class */ (function (_super) {
  36453. __extends(PlaneGeometry, _super);
  36454. /**
  36455. * Creates a plane geometry
  36456. * @param id defines the unique ID of the geometry
  36457. * @param scene defines the hosting scene
  36458. * @param size defines the size of the plane (width === height)
  36459. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36460. * @param mesh defines the hosting mesh (can be null)
  36461. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36462. */
  36463. function PlaneGeometry(id, scene,
  36464. /**
  36465. * Defines the size of the plane (width === height)
  36466. */
  36467. size, canBeRegenerated, mesh,
  36468. /**
  36469. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36470. */
  36471. side) {
  36472. if (mesh === void 0) { mesh = null; }
  36473. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36474. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36475. _this.size = size;
  36476. _this.side = side;
  36477. return _this;
  36478. }
  36479. PlaneGeometry.prototype._regenerateVertexData = function () {
  36480. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36481. };
  36482. PlaneGeometry.prototype.copy = function (id) {
  36483. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36484. };
  36485. PlaneGeometry.prototype.serialize = function () {
  36486. var serializationObject = _super.prototype.serialize.call(this);
  36487. serializationObject.size = this.size;
  36488. return serializationObject;
  36489. };
  36490. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36491. if (scene.getGeometryByID(parsedPlane.id)) {
  36492. return null; // null since geometry could be something else than a ground...
  36493. }
  36494. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36495. if (BABYLON.Tags) {
  36496. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36497. }
  36498. scene.pushGeometry(plane, true);
  36499. return plane;
  36500. };
  36501. return PlaneGeometry;
  36502. }(_PrimitiveGeometry));
  36503. BABYLON.PlaneGeometry = PlaneGeometry;
  36504. /**
  36505. * Creates a torus knot geometry
  36506. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36507. */
  36508. var TorusKnotGeometry = /** @class */ (function (_super) {
  36509. __extends(TorusKnotGeometry, _super);
  36510. /**
  36511. * Creates a torus knot geometry
  36512. * @param id defines the unique ID of the geometry
  36513. * @param scene defines the hosting scene
  36514. * @param radius defines the radius of the torus knot
  36515. * @param tube defines the thickness of the torus knot tube
  36516. * @param radialSegments defines the number of radial segments
  36517. * @param tubularSegments defines the number of tubular segments
  36518. * @param p defines the first number of windings
  36519. * @param q defines the second number of windings
  36520. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36521. * @param mesh defines the hosting mesh (can be null)
  36522. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36523. */
  36524. function TorusKnotGeometry(id, scene,
  36525. /**
  36526. * Defines the radius of the torus knot
  36527. */
  36528. radius,
  36529. /**
  36530. * Defines the thickness of the torus knot tube
  36531. */
  36532. tube,
  36533. /**
  36534. * Defines the number of radial segments
  36535. */
  36536. radialSegments,
  36537. /**
  36538. * Defines the number of tubular segments
  36539. */
  36540. tubularSegments,
  36541. /**
  36542. * Defines the first number of windings
  36543. */
  36544. p,
  36545. /**
  36546. * Defines the second number of windings
  36547. */
  36548. q, canBeRegenerated, mesh,
  36549. /**
  36550. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36551. */
  36552. side) {
  36553. if (mesh === void 0) { mesh = null; }
  36554. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36555. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36556. _this.radius = radius;
  36557. _this.tube = tube;
  36558. _this.radialSegments = radialSegments;
  36559. _this.tubularSegments = tubularSegments;
  36560. _this.p = p;
  36561. _this.q = q;
  36562. _this.side = side;
  36563. return _this;
  36564. }
  36565. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36566. 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 });
  36567. };
  36568. TorusKnotGeometry.prototype.copy = function (id) {
  36569. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36570. };
  36571. TorusKnotGeometry.prototype.serialize = function () {
  36572. var serializationObject = _super.prototype.serialize.call(this);
  36573. serializationObject.radius = this.radius;
  36574. serializationObject.tube = this.tube;
  36575. serializationObject.radialSegments = this.radialSegments;
  36576. serializationObject.tubularSegments = this.tubularSegments;
  36577. serializationObject.p = this.p;
  36578. serializationObject.q = this.q;
  36579. return serializationObject;
  36580. };
  36581. ;
  36582. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36583. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36584. return null; // null since geometry could be something else than a ground...
  36585. }
  36586. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36587. if (BABYLON.Tags) {
  36588. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36589. }
  36590. scene.pushGeometry(torusKnot, true);
  36591. return torusKnot;
  36592. };
  36593. return TorusKnotGeometry;
  36594. }(_PrimitiveGeometry));
  36595. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36596. //}
  36597. })(BABYLON || (BABYLON = {}));
  36598. //# sourceMappingURL=babylon.geometry.js.map
  36599. var BABYLON;
  36600. (function (BABYLON) {
  36601. /**
  36602. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36603. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36604. */
  36605. var PostProcessManager = /** @class */ (function () {
  36606. /**
  36607. * Creates a new instance of @see PostProcess
  36608. * @param scene The scene that the post process is associated with.
  36609. */
  36610. function PostProcessManager(scene) {
  36611. this._vertexBuffers = {};
  36612. this._scene = scene;
  36613. }
  36614. PostProcessManager.prototype._prepareBuffers = function () {
  36615. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36616. return;
  36617. }
  36618. // VBO
  36619. var vertices = [];
  36620. vertices.push(1, 1);
  36621. vertices.push(-1, 1);
  36622. vertices.push(-1, -1);
  36623. vertices.push(1, -1);
  36624. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36625. this._buildIndexBuffer();
  36626. };
  36627. PostProcessManager.prototype._buildIndexBuffer = function () {
  36628. // Indices
  36629. var indices = [];
  36630. indices.push(0);
  36631. indices.push(1);
  36632. indices.push(2);
  36633. indices.push(0);
  36634. indices.push(2);
  36635. indices.push(3);
  36636. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36637. };
  36638. /**
  36639. * Rebuilds the vertex buffers of the manager.
  36640. */
  36641. PostProcessManager.prototype._rebuild = function () {
  36642. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36643. if (!vb) {
  36644. return;
  36645. }
  36646. vb._rebuild();
  36647. this._buildIndexBuffer();
  36648. };
  36649. // Methods
  36650. /**
  36651. * Prepares a frame to be run through a post process.
  36652. * @param sourceTexture The input texture to the post procesess. (default: null)
  36653. * @param postProcesses An array of post processes to be run. (default: null)
  36654. * @returns True if the post processes were able to be run.
  36655. */
  36656. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36657. if (sourceTexture === void 0) { sourceTexture = null; }
  36658. if (postProcesses === void 0) { postProcesses = null; }
  36659. var camera = this._scene.activeCamera;
  36660. if (!camera) {
  36661. return false;
  36662. }
  36663. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36664. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36665. return false;
  36666. }
  36667. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36668. return true;
  36669. };
  36670. /**
  36671. * Manually render a set of post processes to a texture.
  36672. * @param postProcesses An array of post processes to be run.
  36673. * @param targetTexture The target texture to render to.
  36674. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36675. */
  36676. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36677. if (targetTexture === void 0) { targetTexture = null; }
  36678. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36679. var engine = this._scene.getEngine();
  36680. for (var index = 0; index < postProcesses.length; index++) {
  36681. if (index < postProcesses.length - 1) {
  36682. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36683. }
  36684. else {
  36685. if (targetTexture) {
  36686. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36687. }
  36688. else {
  36689. engine.restoreDefaultFramebuffer();
  36690. }
  36691. }
  36692. var pp = postProcesses[index];
  36693. var effect = pp.apply();
  36694. if (effect) {
  36695. pp.onBeforeRenderObservable.notifyObservers(effect);
  36696. // VBOs
  36697. this._prepareBuffers();
  36698. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36699. // Draw order
  36700. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36701. pp.onAfterRenderObservable.notifyObservers(effect);
  36702. }
  36703. }
  36704. // Restore depth buffer
  36705. engine.setDepthBuffer(true);
  36706. engine.setDepthWrite(true);
  36707. };
  36708. /**
  36709. * Finalize the result of the output of the postprocesses.
  36710. * @param doNotPresent If true the result will not be displayed to the screen.
  36711. * @param targetTexture The target texture to render to.
  36712. * @param faceIndex The index of the face to bind the target texture to.
  36713. * @param postProcesses The array of post processes to render.
  36714. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36715. */
  36716. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36717. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36718. var camera = this._scene.activeCamera;
  36719. if (!camera) {
  36720. return;
  36721. }
  36722. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36723. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36724. return;
  36725. }
  36726. var engine = this._scene.getEngine();
  36727. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36728. if (index < len - 1) {
  36729. postProcesses[index + 1].activate(camera, targetTexture);
  36730. }
  36731. else {
  36732. if (targetTexture) {
  36733. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36734. }
  36735. else {
  36736. engine.restoreDefaultFramebuffer();
  36737. }
  36738. }
  36739. if (doNotPresent) {
  36740. break;
  36741. }
  36742. var pp = postProcesses[index];
  36743. var effect = pp.apply();
  36744. if (effect) {
  36745. pp.onBeforeRenderObservable.notifyObservers(effect);
  36746. // VBOs
  36747. this._prepareBuffers();
  36748. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36749. // Draw order
  36750. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36751. pp.onAfterRenderObservable.notifyObservers(effect);
  36752. }
  36753. }
  36754. // Restore states
  36755. engine.setDepthBuffer(true);
  36756. engine.setDepthWrite(true);
  36757. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36758. };
  36759. /**
  36760. * Disposes of the post process manager.
  36761. */
  36762. PostProcessManager.prototype.dispose = function () {
  36763. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36764. if (buffer) {
  36765. buffer.dispose();
  36766. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36767. }
  36768. if (this._indexBuffer) {
  36769. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36770. this._indexBuffer = null;
  36771. }
  36772. };
  36773. return PostProcessManager;
  36774. }());
  36775. BABYLON.PostProcessManager = PostProcessManager;
  36776. })(BABYLON || (BABYLON = {}));
  36777. //# sourceMappingURL=babylon.postProcessManager.js.map
  36778. var BABYLON;
  36779. (function (BABYLON) {
  36780. /**
  36781. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36782. */
  36783. var PerformanceMonitor = /** @class */ (function () {
  36784. /**
  36785. * constructor
  36786. * @param frameSampleSize The number of samples required to saturate the sliding window
  36787. */
  36788. function PerformanceMonitor(frameSampleSize) {
  36789. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36790. this._enabled = true;
  36791. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36792. }
  36793. /**
  36794. * Samples current frame
  36795. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36796. */
  36797. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36798. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36799. if (!this._enabled)
  36800. return;
  36801. if (this._lastFrameTimeMs != null) {
  36802. var dt = timeMs - this._lastFrameTimeMs;
  36803. this._rollingFrameTime.add(dt);
  36804. }
  36805. this._lastFrameTimeMs = timeMs;
  36806. };
  36807. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36808. /**
  36809. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36810. * @return Average frame time in milliseconds
  36811. */
  36812. get: function () {
  36813. return this._rollingFrameTime.average;
  36814. },
  36815. enumerable: true,
  36816. configurable: true
  36817. });
  36818. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36819. /**
  36820. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36821. * @return Frame time variance in milliseconds squared
  36822. */
  36823. get: function () {
  36824. return this._rollingFrameTime.variance;
  36825. },
  36826. enumerable: true,
  36827. configurable: true
  36828. });
  36829. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36830. /**
  36831. * Returns the frame time of the most recent frame
  36832. * @return Frame time in milliseconds
  36833. */
  36834. get: function () {
  36835. return this._rollingFrameTime.history(0);
  36836. },
  36837. enumerable: true,
  36838. configurable: true
  36839. });
  36840. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36841. /**
  36842. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36843. * @return Framerate in frames per second
  36844. */
  36845. get: function () {
  36846. return 1000.0 / this._rollingFrameTime.average;
  36847. },
  36848. enumerable: true,
  36849. configurable: true
  36850. });
  36851. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36852. /**
  36853. * Returns the average framerate in frames per second using the most recent frame time
  36854. * @return Framerate in frames per second
  36855. */
  36856. get: function () {
  36857. var history = this._rollingFrameTime.history(0);
  36858. if (history === 0) {
  36859. return 0;
  36860. }
  36861. return 1000.0 / history;
  36862. },
  36863. enumerable: true,
  36864. configurable: true
  36865. });
  36866. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36867. /**
  36868. * Returns true if enough samples have been taken to completely fill the sliding window
  36869. * @return true if saturated
  36870. */
  36871. get: function () {
  36872. return this._rollingFrameTime.isSaturated();
  36873. },
  36874. enumerable: true,
  36875. configurable: true
  36876. });
  36877. /**
  36878. * Enables contributions to the sliding window sample set
  36879. */
  36880. PerformanceMonitor.prototype.enable = function () {
  36881. this._enabled = true;
  36882. };
  36883. /**
  36884. * Disables contributions to the sliding window sample set
  36885. * Samples will not be interpolated over the disabled period
  36886. */
  36887. PerformanceMonitor.prototype.disable = function () {
  36888. this._enabled = false;
  36889. //clear last sample to avoid interpolating over the disabled period when next enabled
  36890. this._lastFrameTimeMs = null;
  36891. };
  36892. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36893. /**
  36894. * Returns true if sampling is enabled
  36895. * @return true if enabled
  36896. */
  36897. get: function () {
  36898. return this._enabled;
  36899. },
  36900. enumerable: true,
  36901. configurable: true
  36902. });
  36903. /**
  36904. * Resets performance monitor
  36905. */
  36906. PerformanceMonitor.prototype.reset = function () {
  36907. //clear last sample to avoid interpolating over the disabled period when next enabled
  36908. this._lastFrameTimeMs = null;
  36909. //wipe record
  36910. this._rollingFrameTime.reset();
  36911. };
  36912. return PerformanceMonitor;
  36913. }());
  36914. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36915. /**
  36916. * RollingAverage
  36917. *
  36918. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36919. */
  36920. var RollingAverage = /** @class */ (function () {
  36921. /**
  36922. * constructor
  36923. * @param length The number of samples required to saturate the sliding window
  36924. */
  36925. function RollingAverage(length) {
  36926. this._samples = new Array(length);
  36927. this.reset();
  36928. }
  36929. /**
  36930. * Adds a sample to the sample set
  36931. * @param v The sample value
  36932. */
  36933. RollingAverage.prototype.add = function (v) {
  36934. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36935. var delta;
  36936. //we need to check if we've already wrapped round
  36937. if (this.isSaturated()) {
  36938. //remove bottom of stack from mean
  36939. var bottomValue = this._samples[this._pos];
  36940. delta = bottomValue - this.average;
  36941. this.average -= delta / (this._sampleCount - 1);
  36942. this._m2 -= delta * (bottomValue - this.average);
  36943. }
  36944. else {
  36945. this._sampleCount++;
  36946. }
  36947. //add new value to mean
  36948. delta = v - this.average;
  36949. this.average += delta / (this._sampleCount);
  36950. this._m2 += delta * (v - this.average);
  36951. //set the new variance
  36952. this.variance = this._m2 / (this._sampleCount - 1);
  36953. this._samples[this._pos] = v;
  36954. this._pos++;
  36955. this._pos %= this._samples.length; //positive wrap around
  36956. };
  36957. /**
  36958. * Returns previously added values or null if outside of history or outside the sliding window domain
  36959. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36960. * @return Value previously recorded with add() or null if outside of range
  36961. */
  36962. RollingAverage.prototype.history = function (i) {
  36963. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36964. return 0;
  36965. }
  36966. var i0 = this._wrapPosition(this._pos - 1.0);
  36967. return this._samples[this._wrapPosition(i0 - i)];
  36968. };
  36969. /**
  36970. * Returns true if enough samples have been taken to completely fill the sliding window
  36971. * @return true if sample-set saturated
  36972. */
  36973. RollingAverage.prototype.isSaturated = function () {
  36974. return this._sampleCount >= this._samples.length;
  36975. };
  36976. /**
  36977. * Resets the rolling average (equivalent to 0 samples taken so far)
  36978. */
  36979. RollingAverage.prototype.reset = function () {
  36980. this.average = 0;
  36981. this.variance = 0;
  36982. this._sampleCount = 0;
  36983. this._pos = 0;
  36984. this._m2 = 0;
  36985. };
  36986. /**
  36987. * Wraps a value around the sample range boundaries
  36988. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36989. * @return Wrapped position in sample range
  36990. */
  36991. RollingAverage.prototype._wrapPosition = function (i) {
  36992. var max = this._samples.length;
  36993. return ((i % max) + max) % max;
  36994. };
  36995. return RollingAverage;
  36996. }());
  36997. BABYLON.RollingAverage = RollingAverage;
  36998. })(BABYLON || (BABYLON = {}));
  36999. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37000. var BABYLON;
  37001. (function (BABYLON) {
  37002. /**
  37003. * This groups together the common properties used for image processing either in direct forward pass
  37004. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37005. * or not.
  37006. */
  37007. var ImageProcessingConfiguration = /** @class */ (function () {
  37008. function ImageProcessingConfiguration() {
  37009. /**
  37010. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37011. */
  37012. this.colorCurves = new BABYLON.ColorCurves();
  37013. this._colorCurvesEnabled = false;
  37014. this._colorGradingEnabled = false;
  37015. this._colorGradingWithGreenDepth = true;
  37016. this._colorGradingBGR = true;
  37017. this._exposure = 1.0;
  37018. this._toneMappingEnabled = false;
  37019. this._contrast = 1.0;
  37020. /**
  37021. * Vignette stretch size.
  37022. */
  37023. this.vignetteStretch = 0;
  37024. /**
  37025. * Vignette centre X Offset.
  37026. */
  37027. this.vignetteCentreX = 0;
  37028. /**
  37029. * Vignette centre Y Offset.
  37030. */
  37031. this.vignetteCentreY = 0;
  37032. /**
  37033. * Vignette weight or intensity of the vignette effect.
  37034. */
  37035. this.vignetteWeight = 1.5;
  37036. /**
  37037. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37038. * if vignetteEnabled is set to true.
  37039. */
  37040. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37041. /**
  37042. * Camera field of view used by the Vignette effect.
  37043. */
  37044. this.vignetteCameraFov = 0.5;
  37045. this._grainEnabled = false;
  37046. this._grainIntensity = 30;
  37047. this._grainAnimated = false;
  37048. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37049. this._vignetteEnabled = false;
  37050. this._applyByPostProcess = false;
  37051. this._isEnabled = true;
  37052. /**
  37053. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37054. * @type {BABYLON.Observable}
  37055. */
  37056. this.onUpdateParameters = new BABYLON.Observable();
  37057. }
  37058. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37059. /**
  37060. * Gets wether the color curves effect is enabled.
  37061. */
  37062. get: function () {
  37063. return this._colorCurvesEnabled;
  37064. },
  37065. /**
  37066. * Sets wether the color curves effect is enabled.
  37067. */
  37068. set: function (value) {
  37069. if (this._colorCurvesEnabled === value) {
  37070. return;
  37071. }
  37072. this._colorCurvesEnabled = value;
  37073. this._updateParameters();
  37074. },
  37075. enumerable: true,
  37076. configurable: true
  37077. });
  37078. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37079. /**
  37080. * Gets wether the color grading effect is enabled.
  37081. */
  37082. get: function () {
  37083. return this._colorGradingEnabled;
  37084. },
  37085. /**
  37086. * Sets wether the color grading effect is enabled.
  37087. */
  37088. set: function (value) {
  37089. if (this._colorGradingEnabled === value) {
  37090. return;
  37091. }
  37092. this._colorGradingEnabled = value;
  37093. this._updateParameters();
  37094. },
  37095. enumerable: true,
  37096. configurable: true
  37097. });
  37098. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37099. /**
  37100. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37101. */
  37102. get: function () {
  37103. return this._colorGradingWithGreenDepth;
  37104. },
  37105. /**
  37106. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37107. */
  37108. set: function (value) {
  37109. if (this._colorGradingWithGreenDepth === value) {
  37110. return;
  37111. }
  37112. this._colorGradingWithGreenDepth = value;
  37113. this._updateParameters();
  37114. },
  37115. enumerable: true,
  37116. configurable: true
  37117. });
  37118. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37119. /**
  37120. * Gets wether the color grading texture contains BGR values.
  37121. */
  37122. get: function () {
  37123. return this._colorGradingBGR;
  37124. },
  37125. /**
  37126. * Sets wether the color grading texture contains BGR values.
  37127. */
  37128. set: function (value) {
  37129. if (this._colorGradingBGR === value) {
  37130. return;
  37131. }
  37132. this._colorGradingBGR = value;
  37133. this._updateParameters();
  37134. },
  37135. enumerable: true,
  37136. configurable: true
  37137. });
  37138. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37139. /**
  37140. * Gets the Exposure used in the effect.
  37141. */
  37142. get: function () {
  37143. return this._exposure;
  37144. },
  37145. /**
  37146. * Sets the Exposure used in the effect.
  37147. */
  37148. set: function (value) {
  37149. if (this._exposure === value) {
  37150. return;
  37151. }
  37152. this._exposure = value;
  37153. this._updateParameters();
  37154. },
  37155. enumerable: true,
  37156. configurable: true
  37157. });
  37158. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37159. /**
  37160. * Gets wether the tone mapping effect is enabled.
  37161. */
  37162. get: function () {
  37163. return this._toneMappingEnabled;
  37164. },
  37165. /**
  37166. * Sets wether the tone mapping effect is enabled.
  37167. */
  37168. set: function (value) {
  37169. if (this._toneMappingEnabled === value) {
  37170. return;
  37171. }
  37172. this._toneMappingEnabled = value;
  37173. this._updateParameters();
  37174. },
  37175. enumerable: true,
  37176. configurable: true
  37177. });
  37178. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37179. /**
  37180. * Gets the contrast used in the effect.
  37181. */
  37182. get: function () {
  37183. return this._contrast;
  37184. },
  37185. /**
  37186. * Sets the contrast used in the effect.
  37187. */
  37188. set: function (value) {
  37189. if (this._contrast === value) {
  37190. return;
  37191. }
  37192. this._contrast = value;
  37193. this._updateParameters();
  37194. },
  37195. enumerable: true,
  37196. configurable: true
  37197. });
  37198. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37199. /**
  37200. * If the grain effect should be enabled.
  37201. */
  37202. get: function () {
  37203. return this._grainEnabled;
  37204. },
  37205. set: function (value) {
  37206. if (this._grainEnabled === value) {
  37207. return;
  37208. }
  37209. this._grainEnabled = value;
  37210. this._updateParameters();
  37211. },
  37212. enumerable: true,
  37213. configurable: true
  37214. });
  37215. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37216. /**
  37217. * Amount of grain to be applied by the grain effect.
  37218. */
  37219. get: function () {
  37220. return this._grainIntensity;
  37221. },
  37222. set: function (value) {
  37223. if (this._grainIntensity === value) {
  37224. return;
  37225. }
  37226. this._grainIntensity = value;
  37227. },
  37228. enumerable: true,
  37229. configurable: true
  37230. });
  37231. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37232. /**
  37233. * If the grain effect should be animated.
  37234. */
  37235. get: function () {
  37236. return this._grainAnimated;
  37237. },
  37238. set: function (value) {
  37239. if (this._grainAnimated === value) {
  37240. return;
  37241. }
  37242. this._grainAnimated = value;
  37243. this._updateParameters();
  37244. },
  37245. enumerable: true,
  37246. configurable: true
  37247. });
  37248. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37249. /**
  37250. * Gets the vignette blend mode allowing different kind of effect.
  37251. */
  37252. get: function () {
  37253. return this._vignetteBlendMode;
  37254. },
  37255. /**
  37256. * Sets the vignette blend mode allowing different kind of effect.
  37257. */
  37258. set: function (value) {
  37259. if (this._vignetteBlendMode === value) {
  37260. return;
  37261. }
  37262. this._vignetteBlendMode = value;
  37263. this._updateParameters();
  37264. },
  37265. enumerable: true,
  37266. configurable: true
  37267. });
  37268. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37269. /**
  37270. * Gets wether the vignette effect is enabled.
  37271. */
  37272. get: function () {
  37273. return this._vignetteEnabled;
  37274. },
  37275. /**
  37276. * Sets wether the vignette effect is enabled.
  37277. */
  37278. set: function (value) {
  37279. if (this._vignetteEnabled === value) {
  37280. return;
  37281. }
  37282. this._vignetteEnabled = value;
  37283. this._updateParameters();
  37284. },
  37285. enumerable: true,
  37286. configurable: true
  37287. });
  37288. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37289. /**
  37290. * Gets wether the image processing is applied through a post process or not.
  37291. */
  37292. get: function () {
  37293. return this._applyByPostProcess;
  37294. },
  37295. /**
  37296. * Sets wether the image processing is applied through a post process or not.
  37297. */
  37298. set: function (value) {
  37299. if (this._applyByPostProcess === value) {
  37300. return;
  37301. }
  37302. this._applyByPostProcess = value;
  37303. this._updateParameters();
  37304. },
  37305. enumerable: true,
  37306. configurable: true
  37307. });
  37308. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37309. /**
  37310. * Gets wether the image processing is enabled or not.
  37311. */
  37312. get: function () {
  37313. return this._isEnabled;
  37314. },
  37315. /**
  37316. * Sets wether the image processing is enabled or not.
  37317. */
  37318. set: function (value) {
  37319. if (this._isEnabled === value) {
  37320. return;
  37321. }
  37322. this._isEnabled = value;
  37323. this._updateParameters();
  37324. },
  37325. enumerable: true,
  37326. configurable: true
  37327. });
  37328. /**
  37329. * Method called each time the image processing information changes requires to recompile the effect.
  37330. */
  37331. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37332. this.onUpdateParameters.notifyObservers(this);
  37333. };
  37334. ImageProcessingConfiguration.prototype.getClassName = function () {
  37335. return "ImageProcessingConfiguration";
  37336. };
  37337. /**
  37338. * Prepare the list of uniforms associated with the Image Processing effects.
  37339. * @param uniformsList The list of uniforms used in the effect
  37340. * @param defines the list of defines currently in use
  37341. */
  37342. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37343. if (defines.EXPOSURE) {
  37344. uniforms.push("exposureLinear");
  37345. }
  37346. if (defines.CONTRAST) {
  37347. uniforms.push("contrast");
  37348. }
  37349. if (defines.COLORGRADING) {
  37350. uniforms.push("colorTransformSettings");
  37351. }
  37352. if (defines.VIGNETTE) {
  37353. uniforms.push("vInverseScreenSize");
  37354. uniforms.push("vignetteSettings1");
  37355. uniforms.push("vignetteSettings2");
  37356. }
  37357. if (defines.COLORCURVES) {
  37358. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37359. }
  37360. if (defines.GRAIN) {
  37361. uniforms.push("grainVarianceAmount");
  37362. uniforms.push("grainAnimatedSeed");
  37363. }
  37364. };
  37365. /**
  37366. * Prepare the list of samplers associated with the Image Processing effects.
  37367. * @param uniformsList The list of uniforms used in the effect
  37368. * @param defines the list of defines currently in use
  37369. */
  37370. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37371. if (defines.COLORGRADING) {
  37372. samplersList.push("txColorTransform");
  37373. }
  37374. };
  37375. /**
  37376. * Prepare the list of defines associated to the shader.
  37377. * @param defines the list of defines to complete
  37378. */
  37379. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37380. if (forPostProcess === void 0) { forPostProcess = false; }
  37381. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37382. defines.VIGNETTE = false;
  37383. defines.TONEMAPPING = false;
  37384. defines.CONTRAST = false;
  37385. defines.EXPOSURE = false;
  37386. defines.COLORCURVES = false;
  37387. defines.COLORGRADING = false;
  37388. defines.COLORGRADING3D = false;
  37389. defines.IMAGEPROCESSING = false;
  37390. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37391. return;
  37392. }
  37393. defines.VIGNETTE = this.vignetteEnabled;
  37394. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37395. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37396. defines.TONEMAPPING = this.toneMappingEnabled;
  37397. defines.CONTRAST = (this.contrast !== 1.0);
  37398. defines.EXPOSURE = (this.exposure !== 1.0);
  37399. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37400. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37401. if (defines.COLORGRADING) {
  37402. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37403. }
  37404. else {
  37405. defines.COLORGRADING3D = false;
  37406. }
  37407. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37408. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37409. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37410. defines.GRAIN = this.grainEnabled;
  37411. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37412. };
  37413. /**
  37414. * Returns true if all the image processing information are ready.
  37415. */
  37416. ImageProcessingConfiguration.prototype.isReady = function () {
  37417. // Color Grading texure can not be none blocking.
  37418. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37419. };
  37420. /**
  37421. * Binds the image processing to the shader.
  37422. * @param effect The effect to bind to
  37423. */
  37424. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37425. if (aspectRatio === void 0) { aspectRatio = 1; }
  37426. // Color Curves
  37427. if (this._colorCurvesEnabled && this.colorCurves) {
  37428. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37429. }
  37430. // Vignette
  37431. if (this._vignetteEnabled) {
  37432. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37433. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37434. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37435. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37436. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37437. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37438. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37439. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37440. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37441. var vignettePower = -2.0 * this.vignetteWeight;
  37442. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37443. }
  37444. // Exposure
  37445. effect.setFloat("exposureLinear", this.exposure);
  37446. // Contrast
  37447. effect.setFloat("contrast", this.contrast);
  37448. // Color transform settings
  37449. if (this.colorGradingTexture) {
  37450. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37451. var textureSize = this.colorGradingTexture.getSize().height;
  37452. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37453. 0.5 / textureSize, // textureOffset
  37454. textureSize, // textureSize
  37455. this.colorGradingTexture.level // weight
  37456. );
  37457. }
  37458. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37459. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37460. };
  37461. /**
  37462. * Clones the current image processing instance.
  37463. * @return The cloned image processing
  37464. */
  37465. ImageProcessingConfiguration.prototype.clone = function () {
  37466. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37467. };
  37468. /**
  37469. * Serializes the current image processing instance to a json representation.
  37470. * @return a JSON representation
  37471. */
  37472. ImageProcessingConfiguration.prototype.serialize = function () {
  37473. return BABYLON.SerializationHelper.Serialize(this);
  37474. };
  37475. /**
  37476. * Parses the image processing from a json representation.
  37477. * @param source the JSON source to parse
  37478. * @return The parsed image processing
  37479. */
  37480. ImageProcessingConfiguration.Parse = function (source) {
  37481. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37482. };
  37483. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37484. /**
  37485. * Used to apply the vignette as a mix with the pixel color.
  37486. */
  37487. get: function () {
  37488. return this._VIGNETTEMODE_MULTIPLY;
  37489. },
  37490. enumerable: true,
  37491. configurable: true
  37492. });
  37493. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37494. /**
  37495. * Used to apply the vignette as a replacement of the pixel color.
  37496. */
  37497. get: function () {
  37498. return this._VIGNETTEMODE_OPAQUE;
  37499. },
  37500. enumerable: true,
  37501. configurable: true
  37502. });
  37503. // Static constants associated to the image processing.
  37504. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37505. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37506. __decorate([
  37507. BABYLON.serializeAsColorCurves()
  37508. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37509. __decorate([
  37510. BABYLON.serialize()
  37511. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37512. __decorate([
  37513. BABYLON.serializeAsTexture()
  37514. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37515. __decorate([
  37516. BABYLON.serialize()
  37517. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37518. __decorate([
  37519. BABYLON.serialize()
  37520. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37521. __decorate([
  37522. BABYLON.serialize()
  37523. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37524. __decorate([
  37525. BABYLON.serialize()
  37526. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37527. __decorate([
  37528. BABYLON.serialize()
  37529. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37530. __decorate([
  37531. BABYLON.serialize()
  37532. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37533. __decorate([
  37534. BABYLON.serialize()
  37535. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37536. __decorate([
  37537. BABYLON.serialize()
  37538. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37539. __decorate([
  37540. BABYLON.serialize()
  37541. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37542. __decorate([
  37543. BABYLON.serialize()
  37544. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37545. __decorate([
  37546. BABYLON.serializeAsColor4()
  37547. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37548. __decorate([
  37549. BABYLON.serialize()
  37550. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37551. __decorate([
  37552. BABYLON.serialize()
  37553. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37554. __decorate([
  37555. BABYLON.serialize()
  37556. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37557. __decorate([
  37558. BABYLON.serialize()
  37559. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37560. __decorate([
  37561. BABYLON.serialize()
  37562. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37563. __decorate([
  37564. BABYLON.serialize()
  37565. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37566. __decorate([
  37567. BABYLON.serialize()
  37568. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37569. __decorate([
  37570. BABYLON.serialize()
  37571. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37572. return ImageProcessingConfiguration;
  37573. }());
  37574. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37575. })(BABYLON || (BABYLON = {}));
  37576. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37577. var BABYLON;
  37578. (function (BABYLON) {
  37579. /**
  37580. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37581. * It can help converting any input color in a desired output one. This can then be used to create effects
  37582. * from sepia, black and white to sixties or futuristic rendering...
  37583. *
  37584. * The only supported format is currently 3dl.
  37585. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37586. */
  37587. var ColorGradingTexture = /** @class */ (function (_super) {
  37588. __extends(ColorGradingTexture, _super);
  37589. /**
  37590. * Instantiates a ColorGradingTexture from the following parameters.
  37591. *
  37592. * @param url The location of the color gradind data (currently only supporting 3dl)
  37593. * @param scene The scene the texture will be used in
  37594. */
  37595. function ColorGradingTexture(url, scene) {
  37596. var _this = _super.call(this, scene) || this;
  37597. if (!url) {
  37598. return _this;
  37599. }
  37600. _this._engine = scene.getEngine();
  37601. _this._textureMatrix = BABYLON.Matrix.Identity();
  37602. _this.name = url;
  37603. _this.url = url;
  37604. _this.hasAlpha = false;
  37605. _this.isCube = false;
  37606. _this.is3D = _this._engine.webGLVersion > 1;
  37607. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37608. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37609. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37610. _this.anisotropicFilteringLevel = 1;
  37611. _this._texture = _this._getFromCache(url, true);
  37612. if (!_this._texture) {
  37613. if (!scene.useDelayedTextureLoading) {
  37614. _this.loadTexture();
  37615. }
  37616. else {
  37617. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37618. }
  37619. }
  37620. return _this;
  37621. }
  37622. /**
  37623. * Returns the texture matrix used in most of the material.
  37624. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37625. */
  37626. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37627. return this._textureMatrix;
  37628. };
  37629. /**
  37630. * Occurs when the file being loaded is a .3dl LUT file.
  37631. */
  37632. ColorGradingTexture.prototype.load3dlTexture = function () {
  37633. var engine = this._engine;
  37634. var texture;
  37635. if (engine.webGLVersion === 1) {
  37636. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37637. }
  37638. else {
  37639. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37640. }
  37641. this._texture = texture;
  37642. var callback = function (text) {
  37643. if (typeof text !== "string") {
  37644. return;
  37645. }
  37646. var data = null;
  37647. var tempData = null;
  37648. var line;
  37649. var lines = text.split('\n');
  37650. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37651. var maxColor = 0;
  37652. for (var i = 0; i < lines.length; i++) {
  37653. line = lines[i];
  37654. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37655. continue;
  37656. if (line.indexOf('#') === 0)
  37657. continue;
  37658. var words = line.split(" ");
  37659. if (size === 0) {
  37660. // Number of space + one
  37661. size = words.length;
  37662. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37663. tempData = new Float32Array(size * size * size * 4);
  37664. continue;
  37665. }
  37666. if (size != 0) {
  37667. var r = Math.max(parseInt(words[0]), 0);
  37668. var g = Math.max(parseInt(words[1]), 0);
  37669. var b = Math.max(parseInt(words[2]), 0);
  37670. maxColor = Math.max(r, maxColor);
  37671. maxColor = Math.max(g, maxColor);
  37672. maxColor = Math.max(b, maxColor);
  37673. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37674. if (tempData) {
  37675. tempData[pixelStorageIndex + 0] = r;
  37676. tempData[pixelStorageIndex + 1] = g;
  37677. tempData[pixelStorageIndex + 2] = b;
  37678. }
  37679. pixelIndexSlice++;
  37680. if (pixelIndexSlice % size == 0) {
  37681. pixelIndexH++;
  37682. pixelIndexSlice = 0;
  37683. if (pixelIndexH % size == 0) {
  37684. pixelIndexW++;
  37685. pixelIndexH = 0;
  37686. }
  37687. }
  37688. }
  37689. }
  37690. if (tempData && data) {
  37691. for (var i = 0; i < tempData.length; i++) {
  37692. if (i > 0 && (i + 1) % 4 === 0) {
  37693. data[i] = 255;
  37694. }
  37695. else {
  37696. var value = tempData[i];
  37697. data[i] = (value / maxColor * 255);
  37698. }
  37699. }
  37700. }
  37701. if (texture.is3D) {
  37702. texture.updateSize(size, size, size);
  37703. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37704. }
  37705. else {
  37706. texture.updateSize(size * size, size);
  37707. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37708. }
  37709. };
  37710. var scene = this.getScene();
  37711. if (scene) {
  37712. scene._loadFile(this.url, callback);
  37713. }
  37714. else {
  37715. this._engine._loadFile(this.url, callback);
  37716. }
  37717. return this._texture;
  37718. };
  37719. /**
  37720. * Starts the loading process of the texture.
  37721. */
  37722. ColorGradingTexture.prototype.loadTexture = function () {
  37723. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37724. this.load3dlTexture();
  37725. }
  37726. };
  37727. /**
  37728. * Clones the color gradind texture.
  37729. */
  37730. ColorGradingTexture.prototype.clone = function () {
  37731. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37732. // Base texture
  37733. newTexture.level = this.level;
  37734. return newTexture;
  37735. };
  37736. /**
  37737. * Called during delayed load for textures.
  37738. */
  37739. ColorGradingTexture.prototype.delayLoad = function () {
  37740. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37741. return;
  37742. }
  37743. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37744. this._texture = this._getFromCache(this.url, true);
  37745. if (!this._texture) {
  37746. this.loadTexture();
  37747. }
  37748. };
  37749. /**
  37750. * Parses a color grading texture serialized by Babylon.
  37751. * @param parsedTexture The texture information being parsedTexture
  37752. * @param scene The scene to load the texture in
  37753. * @param rootUrl The root url of the data assets to load
  37754. * @return A color gradind texture
  37755. */
  37756. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37757. var texture = null;
  37758. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37759. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37760. texture.name = parsedTexture.name;
  37761. texture.level = parsedTexture.level;
  37762. }
  37763. return texture;
  37764. };
  37765. /**
  37766. * Serializes the LUT texture to json format.
  37767. */
  37768. ColorGradingTexture.prototype.serialize = function () {
  37769. if (!this.name) {
  37770. return null;
  37771. }
  37772. var serializationObject = {};
  37773. serializationObject.name = this.name;
  37774. serializationObject.level = this.level;
  37775. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37776. return serializationObject;
  37777. };
  37778. /**
  37779. * Empty line regex stored for GC.
  37780. */
  37781. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37782. return ColorGradingTexture;
  37783. }(BABYLON.BaseTexture));
  37784. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37785. })(BABYLON || (BABYLON = {}));
  37786. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37787. var BABYLON;
  37788. (function (BABYLON) {
  37789. /**
  37790. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37791. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37792. * 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;
  37793. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37794. */
  37795. var ColorCurves = /** @class */ (function () {
  37796. function ColorCurves() {
  37797. this._dirty = true;
  37798. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37799. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37800. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37801. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37802. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37803. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37804. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37805. this._globalHue = 30;
  37806. this._globalDensity = 0;
  37807. this._globalSaturation = 0;
  37808. this._globalExposure = 0;
  37809. this._highlightsHue = 30;
  37810. this._highlightsDensity = 0;
  37811. this._highlightsSaturation = 0;
  37812. this._highlightsExposure = 0;
  37813. this._midtonesHue = 30;
  37814. this._midtonesDensity = 0;
  37815. this._midtonesSaturation = 0;
  37816. this._midtonesExposure = 0;
  37817. this._shadowsHue = 30;
  37818. this._shadowsDensity = 0;
  37819. this._shadowsSaturation = 0;
  37820. this._shadowsExposure = 0;
  37821. }
  37822. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37823. /**
  37824. * Gets the global Hue value.
  37825. * 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).
  37826. */
  37827. get: function () {
  37828. return this._globalHue;
  37829. },
  37830. /**
  37831. * Sets the global Hue value.
  37832. * 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).
  37833. */
  37834. set: function (value) {
  37835. this._globalHue = value;
  37836. this._dirty = true;
  37837. },
  37838. enumerable: true,
  37839. configurable: true
  37840. });
  37841. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37842. /**
  37843. * Gets the global Density value.
  37844. * 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.
  37845. * Values less than zero provide a filter of opposite hue.
  37846. */
  37847. get: function () {
  37848. return this._globalDensity;
  37849. },
  37850. /**
  37851. * Sets the global Density value.
  37852. * 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.
  37853. * Values less than zero provide a filter of opposite hue.
  37854. */
  37855. set: function (value) {
  37856. this._globalDensity = value;
  37857. this._dirty = true;
  37858. },
  37859. enumerable: true,
  37860. configurable: true
  37861. });
  37862. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37863. /**
  37864. * Gets the global Saturation value.
  37865. * 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.
  37866. */
  37867. get: function () {
  37868. return this._globalSaturation;
  37869. },
  37870. /**
  37871. * Sets the global Saturation value.
  37872. * 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.
  37873. */
  37874. set: function (value) {
  37875. this._globalSaturation = value;
  37876. this._dirty = true;
  37877. },
  37878. enumerable: true,
  37879. configurable: true
  37880. });
  37881. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37882. /**
  37883. * Gets the highlights Hue value.
  37884. * 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).
  37885. */
  37886. get: function () {
  37887. return this._highlightsHue;
  37888. },
  37889. /**
  37890. * Sets the highlights Hue value.
  37891. * 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).
  37892. */
  37893. set: function (value) {
  37894. this._highlightsHue = value;
  37895. this._dirty = true;
  37896. },
  37897. enumerable: true,
  37898. configurable: true
  37899. });
  37900. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37901. /**
  37902. * Gets the highlights Density value.
  37903. * 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.
  37904. * Values less than zero provide a filter of opposite hue.
  37905. */
  37906. get: function () {
  37907. return this._highlightsDensity;
  37908. },
  37909. /**
  37910. * Sets the highlights Density value.
  37911. * 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.
  37912. * Values less than zero provide a filter of opposite hue.
  37913. */
  37914. set: function (value) {
  37915. this._highlightsDensity = value;
  37916. this._dirty = true;
  37917. },
  37918. enumerable: true,
  37919. configurable: true
  37920. });
  37921. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37922. /**
  37923. * Gets the highlights Saturation value.
  37924. * 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.
  37925. */
  37926. get: function () {
  37927. return this._highlightsSaturation;
  37928. },
  37929. /**
  37930. * Sets the highlights Saturation value.
  37931. * 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.
  37932. */
  37933. set: function (value) {
  37934. this._highlightsSaturation = value;
  37935. this._dirty = true;
  37936. },
  37937. enumerable: true,
  37938. configurable: true
  37939. });
  37940. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37941. /**
  37942. * Gets the highlights Exposure value.
  37943. * 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.
  37944. */
  37945. get: function () {
  37946. return this._highlightsExposure;
  37947. },
  37948. /**
  37949. * Sets the highlights Exposure value.
  37950. * 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.
  37951. */
  37952. set: function (value) {
  37953. this._highlightsExposure = value;
  37954. this._dirty = true;
  37955. },
  37956. enumerable: true,
  37957. configurable: true
  37958. });
  37959. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37960. /**
  37961. * Gets the midtones Hue value.
  37962. * 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).
  37963. */
  37964. get: function () {
  37965. return this._midtonesHue;
  37966. },
  37967. /**
  37968. * Sets the midtones Hue value.
  37969. * 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).
  37970. */
  37971. set: function (value) {
  37972. this._midtonesHue = value;
  37973. this._dirty = true;
  37974. },
  37975. enumerable: true,
  37976. configurable: true
  37977. });
  37978. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37979. /**
  37980. * Gets the midtones Density value.
  37981. * 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.
  37982. * Values less than zero provide a filter of opposite hue.
  37983. */
  37984. get: function () {
  37985. return this._midtonesDensity;
  37986. },
  37987. /**
  37988. * Sets the midtones Density value.
  37989. * 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.
  37990. * Values less than zero provide a filter of opposite hue.
  37991. */
  37992. set: function (value) {
  37993. this._midtonesDensity = value;
  37994. this._dirty = true;
  37995. },
  37996. enumerable: true,
  37997. configurable: true
  37998. });
  37999. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38000. /**
  38001. * Gets the midtones Saturation value.
  38002. * 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.
  38003. */
  38004. get: function () {
  38005. return this._midtonesSaturation;
  38006. },
  38007. /**
  38008. * Sets the midtones Saturation value.
  38009. * 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.
  38010. */
  38011. set: function (value) {
  38012. this._midtonesSaturation = value;
  38013. this._dirty = true;
  38014. },
  38015. enumerable: true,
  38016. configurable: true
  38017. });
  38018. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38019. /**
  38020. * Gets the midtones Exposure value.
  38021. * 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.
  38022. */
  38023. get: function () {
  38024. return this._midtonesExposure;
  38025. },
  38026. /**
  38027. * Sets the midtones Exposure value.
  38028. * 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.
  38029. */
  38030. set: function (value) {
  38031. this._midtonesExposure = value;
  38032. this._dirty = true;
  38033. },
  38034. enumerable: true,
  38035. configurable: true
  38036. });
  38037. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38038. /**
  38039. * Gets the shadows Hue value.
  38040. * 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).
  38041. */
  38042. get: function () {
  38043. return this._shadowsHue;
  38044. },
  38045. /**
  38046. * Sets the shadows Hue value.
  38047. * 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).
  38048. */
  38049. set: function (value) {
  38050. this._shadowsHue = value;
  38051. this._dirty = true;
  38052. },
  38053. enumerable: true,
  38054. configurable: true
  38055. });
  38056. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38057. /**
  38058. * Gets the shadows Density value.
  38059. * 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.
  38060. * Values less than zero provide a filter of opposite hue.
  38061. */
  38062. get: function () {
  38063. return this._shadowsDensity;
  38064. },
  38065. /**
  38066. * Sets the shadows Density value.
  38067. * 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.
  38068. * Values less than zero provide a filter of opposite hue.
  38069. */
  38070. set: function (value) {
  38071. this._shadowsDensity = value;
  38072. this._dirty = true;
  38073. },
  38074. enumerable: true,
  38075. configurable: true
  38076. });
  38077. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38078. /**
  38079. * Gets the shadows Saturation value.
  38080. * 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.
  38081. */
  38082. get: function () {
  38083. return this._shadowsSaturation;
  38084. },
  38085. /**
  38086. * Sets the shadows Saturation value.
  38087. * 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.
  38088. */
  38089. set: function (value) {
  38090. this._shadowsSaturation = value;
  38091. this._dirty = true;
  38092. },
  38093. enumerable: true,
  38094. configurable: true
  38095. });
  38096. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38097. /**
  38098. * Gets the shadows Exposure value.
  38099. * 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.
  38100. */
  38101. get: function () {
  38102. return this._shadowsExposure;
  38103. },
  38104. /**
  38105. * Sets the shadows Exposure value.
  38106. * 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.
  38107. */
  38108. set: function (value) {
  38109. this._shadowsExposure = value;
  38110. this._dirty = true;
  38111. },
  38112. enumerable: true,
  38113. configurable: true
  38114. });
  38115. ColorCurves.prototype.getClassName = function () {
  38116. return "ColorCurves";
  38117. };
  38118. /**
  38119. * Binds the color curves to the shader.
  38120. * @param colorCurves The color curve to bind
  38121. * @param effect The effect to bind to
  38122. */
  38123. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38124. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38125. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38126. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38127. if (colorCurves._dirty) {
  38128. colorCurves._dirty = false;
  38129. // Fill in global info.
  38130. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38131. // Compute highlights info.
  38132. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38133. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38134. // Compute midtones info.
  38135. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38136. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38137. // Compute shadows info.
  38138. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38139. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38140. // Compute deltas (neutral is midtones).
  38141. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38142. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38143. }
  38144. if (effect) {
  38145. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38146. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38147. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38148. }
  38149. };
  38150. /**
  38151. * Prepare the list of uniforms associated with the ColorCurves effects.
  38152. * @param uniformsList The list of uniforms used in the effect
  38153. */
  38154. ColorCurves.PrepareUniforms = function (uniformsList) {
  38155. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38156. };
  38157. /**
  38158. * Returns color grading data based on a hue, density, saturation and exposure value.
  38159. * @param filterHue The hue of the color filter.
  38160. * @param filterDensity The density of the color filter.
  38161. * @param saturation The saturation.
  38162. * @param exposure The exposure.
  38163. * @param result The result data container.
  38164. */
  38165. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38166. if (hue == null) {
  38167. return;
  38168. }
  38169. hue = ColorCurves.clamp(hue, 0, 360);
  38170. density = ColorCurves.clamp(density, -100, 100);
  38171. saturation = ColorCurves.clamp(saturation, -100, 100);
  38172. exposure = ColorCurves.clamp(exposure, -100, 100);
  38173. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38174. // so that the maximum filter density is only 50% control. This provides fine control
  38175. // for small values and reasonable range.
  38176. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38177. density *= 0.5;
  38178. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38179. if (density < 0) {
  38180. density *= -1;
  38181. hue = (hue + 180) % 360;
  38182. }
  38183. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38184. result.scaleToRef(2, result);
  38185. result.a = 1 + 0.01 * saturation;
  38186. };
  38187. /**
  38188. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38189. * @param value The input slider value in range [-100,100].
  38190. * @returns Adjusted value.
  38191. */
  38192. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38193. value /= 100;
  38194. var x = Math.abs(value);
  38195. x = Math.pow(x, 2);
  38196. if (value < 0) {
  38197. x *= -1;
  38198. }
  38199. x *= 100;
  38200. return x;
  38201. };
  38202. /**
  38203. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38204. * @param hue The hue (H) input.
  38205. * @param saturation The saturation (S) input.
  38206. * @param brightness The brightness (B) input.
  38207. * @result An RGBA color represented as Vector4.
  38208. */
  38209. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38210. var h = ColorCurves.clamp(hue, 0, 360);
  38211. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38212. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38213. if (s === 0) {
  38214. result.r = v;
  38215. result.g = v;
  38216. result.b = v;
  38217. }
  38218. else {
  38219. // sector 0 to 5
  38220. h /= 60;
  38221. var i = Math.floor(h);
  38222. // fractional part of h
  38223. var f = h - i;
  38224. var p = v * (1 - s);
  38225. var q = v * (1 - s * f);
  38226. var t = v * (1 - s * (1 - f));
  38227. switch (i) {
  38228. case 0:
  38229. result.r = v;
  38230. result.g = t;
  38231. result.b = p;
  38232. break;
  38233. case 1:
  38234. result.r = q;
  38235. result.g = v;
  38236. result.b = p;
  38237. break;
  38238. case 2:
  38239. result.r = p;
  38240. result.g = v;
  38241. result.b = t;
  38242. break;
  38243. case 3:
  38244. result.r = p;
  38245. result.g = q;
  38246. result.b = v;
  38247. break;
  38248. case 4:
  38249. result.r = t;
  38250. result.g = p;
  38251. result.b = v;
  38252. break;
  38253. default:// case 5:
  38254. result.r = v;
  38255. result.g = p;
  38256. result.b = q;
  38257. break;
  38258. }
  38259. }
  38260. result.a = 1;
  38261. };
  38262. /**
  38263. * Returns a value clamped between min and max
  38264. * @param value The value to clamp
  38265. * @param min The minimum of value
  38266. * @param max The maximum of value
  38267. * @returns The clamped value.
  38268. */
  38269. ColorCurves.clamp = function (value, min, max) {
  38270. return Math.min(Math.max(value, min), max);
  38271. };
  38272. /**
  38273. * Clones the current color curve instance.
  38274. * @return The cloned curves
  38275. */
  38276. ColorCurves.prototype.clone = function () {
  38277. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38278. };
  38279. /**
  38280. * Serializes the current color curve instance to a json representation.
  38281. * @return a JSON representation
  38282. */
  38283. ColorCurves.prototype.serialize = function () {
  38284. return BABYLON.SerializationHelper.Serialize(this);
  38285. };
  38286. /**
  38287. * Parses the color curve from a json representation.
  38288. * @param source the JSON source to parse
  38289. * @return The parsed curves
  38290. */
  38291. ColorCurves.Parse = function (source) {
  38292. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38293. };
  38294. __decorate([
  38295. BABYLON.serialize()
  38296. ], ColorCurves.prototype, "_globalHue", void 0);
  38297. __decorate([
  38298. BABYLON.serialize()
  38299. ], ColorCurves.prototype, "_globalDensity", void 0);
  38300. __decorate([
  38301. BABYLON.serialize()
  38302. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38303. __decorate([
  38304. BABYLON.serialize()
  38305. ], ColorCurves.prototype, "_globalExposure", void 0);
  38306. __decorate([
  38307. BABYLON.serialize()
  38308. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38309. __decorate([
  38310. BABYLON.serialize()
  38311. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38312. __decorate([
  38313. BABYLON.serialize()
  38314. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38315. __decorate([
  38316. BABYLON.serialize()
  38317. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38318. __decorate([
  38319. BABYLON.serialize()
  38320. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38321. __decorate([
  38322. BABYLON.serialize()
  38323. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38324. __decorate([
  38325. BABYLON.serialize()
  38326. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38327. __decorate([
  38328. BABYLON.serialize()
  38329. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38330. return ColorCurves;
  38331. }());
  38332. BABYLON.ColorCurves = ColorCurves;
  38333. })(BABYLON || (BABYLON = {}));
  38334. //# sourceMappingURL=babylon.colorCurves.js.map
  38335. //# sourceMappingURL=babylon.behavior.js.map
  38336. var BABYLON;
  38337. (function (BABYLON) {
  38338. /**
  38339. * "Static Class" containing the most commonly used helper while dealing with material for
  38340. * rendering purpose.
  38341. *
  38342. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38343. *
  38344. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38345. */
  38346. var MaterialHelper = /** @class */ (function () {
  38347. function MaterialHelper() {
  38348. }
  38349. /**
  38350. * Bind the current view position to an effect.
  38351. * @param effect The effect to be bound
  38352. * @param scene The scene the eyes position is used from
  38353. */
  38354. MaterialHelper.BindEyePosition = function (effect, scene) {
  38355. if (scene._forcedViewPosition) {
  38356. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38357. return;
  38358. }
  38359. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38360. };
  38361. /**
  38362. * Helps preparing the defines values about the UVs in used in the effect.
  38363. * UVs are shared as much as we can accross chanels in the shaders.
  38364. * @param texture The texture we are preparing the UVs for
  38365. * @param defines The defines to update
  38366. * @param key The chanel key "diffuse", "specular"... used in the shader
  38367. */
  38368. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38369. defines._needUVs = true;
  38370. defines[key] = true;
  38371. if (texture.getTextureMatrix().isIdentity(true)) {
  38372. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38373. if (texture.coordinatesIndex === 0) {
  38374. defines["MAINUV1"] = true;
  38375. }
  38376. else {
  38377. defines["MAINUV2"] = true;
  38378. }
  38379. }
  38380. else {
  38381. defines[key + "DIRECTUV"] = 0;
  38382. }
  38383. };
  38384. /**
  38385. * Binds a texture matrix value to its corrsponding uniform
  38386. * @param texture The texture to bind the matrix for
  38387. * @param uniformBuffer The uniform buffer receivin the data
  38388. * @param key The chanel key "diffuse", "specular"... used in the shader
  38389. */
  38390. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38391. var matrix = texture.getTextureMatrix();
  38392. if (!matrix.isIdentity(true)) {
  38393. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38394. }
  38395. };
  38396. /**
  38397. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38398. * @param mesh defines the current mesh
  38399. * @param scene defines the current scene
  38400. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38401. * @param pointsCloud defines if point cloud rendering has to be turned on
  38402. * @param fogEnabled defines if fog has to be turned on
  38403. * @param alphaTest defines if alpha testing has to be turned on
  38404. * @param defines defines the current list of defines
  38405. */
  38406. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38407. if (defines._areMiscDirty) {
  38408. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38409. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38410. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38411. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38412. defines["ALPHATEST"] = alphaTest;
  38413. }
  38414. };
  38415. /**
  38416. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38417. * @param scene defines the current scene
  38418. * @param engine defines the current engine
  38419. * @param defines specifies the list of active defines
  38420. * @param useInstances defines if instances have to be turned on
  38421. * @param useClipPlane defines if clip plane have to be turned on
  38422. */
  38423. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38424. if (useClipPlane === void 0) { useClipPlane = null; }
  38425. var changed = false;
  38426. if (useClipPlane == null) {
  38427. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38428. }
  38429. if (defines["CLIPPLANE"] !== useClipPlane) {
  38430. defines["CLIPPLANE"] = useClipPlane;
  38431. changed = true;
  38432. }
  38433. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38434. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38435. changed = true;
  38436. }
  38437. if (defines["INSTANCES"] !== useInstances) {
  38438. defines["INSTANCES"] = useInstances;
  38439. changed = true;
  38440. }
  38441. if (changed) {
  38442. defines.markAsUnprocessed();
  38443. }
  38444. };
  38445. /**
  38446. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38447. * @param mesh The mesh containing the geometry data we will draw
  38448. * @param defines The defines to update
  38449. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38450. * @param useBones Precise whether bones should be used or not (override mesh info)
  38451. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38452. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38453. * @returns false if defines are considered not dirty and have not been checked
  38454. */
  38455. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38456. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38457. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38458. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38459. return false;
  38460. }
  38461. defines._normals = defines._needNormals;
  38462. defines._uvs = defines._needUVs;
  38463. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38464. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38465. defines["TANGENT"] = true;
  38466. }
  38467. if (defines._needUVs) {
  38468. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38469. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38470. }
  38471. else {
  38472. defines["UV1"] = false;
  38473. defines["UV2"] = false;
  38474. }
  38475. if (useVertexColor) {
  38476. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38477. defines["VERTEXCOLOR"] = hasVertexColors;
  38478. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38479. }
  38480. if (useBones) {
  38481. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38482. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38483. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38484. }
  38485. else {
  38486. defines["NUM_BONE_INFLUENCERS"] = 0;
  38487. defines["BonesPerMesh"] = 0;
  38488. }
  38489. }
  38490. if (useMorphTargets) {
  38491. var manager = mesh.morphTargetManager;
  38492. if (manager) {
  38493. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38494. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38495. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38496. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38497. }
  38498. else {
  38499. defines["MORPHTARGETS_TANGENT"] = false;
  38500. defines["MORPHTARGETS_NORMAL"] = false;
  38501. defines["MORPHTARGETS"] = false;
  38502. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38503. }
  38504. }
  38505. return true;
  38506. };
  38507. /**
  38508. * Prepares the defines related to the light information passed in parameter
  38509. * @param scene The scene we are intending to draw
  38510. * @param mesh The mesh the effect is compiling for
  38511. * @param defines The defines to update
  38512. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38513. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38514. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38515. * @returns true if normals will be required for the rest of the effect
  38516. */
  38517. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38518. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38519. if (disableLighting === void 0) { disableLighting = false; }
  38520. if (!defines._areLightsDirty) {
  38521. return defines._needNormals;
  38522. }
  38523. var lightIndex = 0;
  38524. var needNormals = false;
  38525. var needRebuild = false;
  38526. var lightmapMode = false;
  38527. var shadowEnabled = false;
  38528. var specularEnabled = false;
  38529. if (scene.lightsEnabled && !disableLighting) {
  38530. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38531. var light = _a[_i];
  38532. needNormals = true;
  38533. if (defines["LIGHT" + lightIndex] === undefined) {
  38534. needRebuild = true;
  38535. }
  38536. defines["LIGHT" + lightIndex] = true;
  38537. defines["SPOTLIGHT" + lightIndex] = false;
  38538. defines["HEMILIGHT" + lightIndex] = false;
  38539. defines["POINTLIGHT" + lightIndex] = false;
  38540. defines["DIRLIGHT" + lightIndex] = false;
  38541. var type;
  38542. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38543. type = "SPOTLIGHT" + lightIndex;
  38544. var spotLight = light;
  38545. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38546. }
  38547. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38548. type = "HEMILIGHT" + lightIndex;
  38549. }
  38550. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38551. type = "POINTLIGHT" + lightIndex;
  38552. }
  38553. else {
  38554. type = "DIRLIGHT" + lightIndex;
  38555. }
  38556. defines[type] = true;
  38557. // Specular
  38558. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38559. specularEnabled = true;
  38560. }
  38561. // Shadows
  38562. defines["SHADOW" + lightIndex] = false;
  38563. defines["SHADOWPCF" + lightIndex] = false;
  38564. defines["SHADOWESM" + lightIndex] = false;
  38565. defines["SHADOWCUBE" + lightIndex] = false;
  38566. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38567. var shadowGenerator = light.getShadowGenerator();
  38568. if (shadowGenerator) {
  38569. shadowEnabled = true;
  38570. shadowGenerator.prepareDefines(defines, lightIndex);
  38571. }
  38572. }
  38573. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38574. lightmapMode = true;
  38575. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38576. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38577. }
  38578. else {
  38579. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38580. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38581. }
  38582. lightIndex++;
  38583. if (lightIndex === maxSimultaneousLights)
  38584. break;
  38585. }
  38586. }
  38587. defines["SPECULARTERM"] = specularEnabled;
  38588. defines["SHADOWS"] = shadowEnabled;
  38589. // Resetting all other lights if any
  38590. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38591. if (defines["LIGHT" + index] !== undefined) {
  38592. defines["LIGHT" + index] = false;
  38593. defines["HEMILIGHT" + lightIndex] = false;
  38594. defines["POINTLIGHT" + lightIndex] = false;
  38595. defines["DIRLIGHT" + lightIndex] = false;
  38596. defines["SPOTLIGHT" + lightIndex] = false;
  38597. defines["SHADOW" + lightIndex] = false;
  38598. }
  38599. }
  38600. var caps = scene.getEngine().getCaps();
  38601. if (defines["SHADOWFLOAT"] === undefined) {
  38602. needRebuild = true;
  38603. }
  38604. defines["SHADOWFLOAT"] = shadowEnabled &&
  38605. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38606. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38607. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38608. if (needRebuild) {
  38609. defines.rebuild();
  38610. }
  38611. return needNormals;
  38612. };
  38613. /**
  38614. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38615. * that won t be acctive due to defines being turned off.
  38616. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38617. * @param samplersList The samplers list
  38618. * @param defines The defines helping in the list generation
  38619. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38620. */
  38621. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38622. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38623. var uniformsList;
  38624. var uniformBuffersList = null;
  38625. if (uniformsListOrOptions.uniformsNames) {
  38626. var options = uniformsListOrOptions;
  38627. uniformsList = options.uniformsNames;
  38628. uniformBuffersList = options.uniformBuffersNames;
  38629. samplersList = options.samplers;
  38630. defines = options.defines;
  38631. maxSimultaneousLights = options.maxSimultaneousLights;
  38632. }
  38633. else {
  38634. uniformsList = uniformsListOrOptions;
  38635. if (!samplersList) {
  38636. samplersList = [];
  38637. }
  38638. }
  38639. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38640. if (!defines["LIGHT" + lightIndex]) {
  38641. break;
  38642. }
  38643. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38644. if (uniformBuffersList) {
  38645. uniformBuffersList.push("Light" + lightIndex);
  38646. }
  38647. samplersList.push("shadowSampler" + lightIndex);
  38648. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38649. samplersList.push("projectionLightSampler" + lightIndex);
  38650. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38651. }
  38652. }
  38653. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38654. uniformsList.push("morphTargetInfluences");
  38655. }
  38656. };
  38657. /**
  38658. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38659. * @param defines The defines to update while falling back
  38660. * @param fallbacks The authorized effect fallbacks
  38661. * @param maxSimultaneousLights The maximum number of lights allowed
  38662. * @param rank the current rank of the Effect
  38663. * @returns The newly affected rank
  38664. */
  38665. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38666. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38667. if (rank === void 0) { rank = 0; }
  38668. var lightFallbackRank = 0;
  38669. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38670. if (!defines["LIGHT" + lightIndex]) {
  38671. break;
  38672. }
  38673. if (lightIndex > 0) {
  38674. lightFallbackRank = rank + lightIndex;
  38675. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38676. }
  38677. if (!defines["SHADOWS"]) {
  38678. if (defines["SHADOW" + lightIndex]) {
  38679. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38680. }
  38681. if (defines["SHADOWPCF" + lightIndex]) {
  38682. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38683. }
  38684. if (defines["SHADOWESM" + lightIndex]) {
  38685. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38686. }
  38687. }
  38688. }
  38689. return lightFallbackRank++;
  38690. };
  38691. /**
  38692. * Prepares the list of attributes required for morph targets according to the effect defines.
  38693. * @param attribs The current list of supported attribs
  38694. * @param mesh The mesh to prepare the morph targets attributes for
  38695. * @param defines The current Defines of the effect
  38696. */
  38697. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38698. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38699. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38700. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38701. var manager = mesh.morphTargetManager;
  38702. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38703. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38704. for (var index = 0; index < influencers; index++) {
  38705. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38706. if (normal) {
  38707. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38708. }
  38709. if (tangent) {
  38710. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38711. }
  38712. if (attribs.length > maxAttributesCount) {
  38713. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38714. }
  38715. }
  38716. }
  38717. };
  38718. /**
  38719. * Prepares the list of attributes required for bones according to the effect defines.
  38720. * @param attribs The current list of supported attribs
  38721. * @param mesh The mesh to prepare the bones attributes for
  38722. * @param defines The current Defines of the effect
  38723. * @param fallbacks The current efffect fallback strategy
  38724. */
  38725. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38726. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38727. fallbacks.addCPUSkinningFallback(0, mesh);
  38728. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38729. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38730. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38731. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38732. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38733. }
  38734. }
  38735. };
  38736. /**
  38737. * Prepares the list of attributes required for instances according to the effect defines.
  38738. * @param attribs The current list of supported attribs
  38739. * @param defines The current Defines of the effect
  38740. */
  38741. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38742. if (defines["INSTANCES"]) {
  38743. attribs.push("world0");
  38744. attribs.push("world1");
  38745. attribs.push("world2");
  38746. attribs.push("world3");
  38747. }
  38748. };
  38749. /**
  38750. * Binds the light shadow information to the effect for the given mesh.
  38751. * @param light The light containing the generator
  38752. * @param scene The scene the lights belongs to
  38753. * @param mesh The mesh we are binding the information to render
  38754. * @param lightIndex The light index in the effect used to render the mesh
  38755. * @param effect The effect we are binding the data to
  38756. */
  38757. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38758. if (light.shadowEnabled && mesh.receiveShadows) {
  38759. var shadowGenerator = light.getShadowGenerator();
  38760. if (shadowGenerator) {
  38761. shadowGenerator.bindShadowLight(lightIndex, effect);
  38762. }
  38763. }
  38764. };
  38765. /**
  38766. * Binds the light information to the effect.
  38767. * @param light The light containing the generator
  38768. * @param effect The effect we are binding the data to
  38769. * @param lightIndex The light index in the effect used to render
  38770. */
  38771. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38772. light.transferToEffect(effect, lightIndex + "");
  38773. };
  38774. /**
  38775. * Binds the lights information from the scene to the effect for the given mesh.
  38776. * @param scene The scene the lights belongs to
  38777. * @param mesh The mesh we are binding the information to render
  38778. * @param effect The effect we are binding the data to
  38779. * @param defines The generated defines for the effect
  38780. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38781. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38782. */
  38783. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38784. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38785. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38786. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38787. for (var i = 0; i < len; i++) {
  38788. var light = mesh._lightSources[i];
  38789. var iAsString = i.toString();
  38790. var scaledIntensity = light.getScaledIntensity();
  38791. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38792. MaterialHelper.BindLightProperties(light, effect, i);
  38793. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38794. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38795. if (defines["SPECULARTERM"]) {
  38796. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38797. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38798. }
  38799. // Shadows
  38800. if (scene.shadowsEnabled) {
  38801. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38802. }
  38803. light._uniformBuffer.update();
  38804. }
  38805. };
  38806. /**
  38807. * Binds the fog information from the scene to the effect for the given mesh.
  38808. * @param scene The scene the lights belongs to
  38809. * @param mesh The mesh we are binding the information to render
  38810. * @param effect The effect we are binding the data to
  38811. */
  38812. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38813. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38814. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38815. effect.setColor3("vFogColor", scene.fogColor);
  38816. }
  38817. };
  38818. /**
  38819. * Binds the bones information from the mesh to the effect.
  38820. * @param mesh The mesh we are binding the information to render
  38821. * @param effect The effect we are binding the data to
  38822. */
  38823. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38824. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38825. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38826. if (matrices && effect) {
  38827. effect.setMatrices("mBones", matrices);
  38828. }
  38829. }
  38830. };
  38831. /**
  38832. * Binds the morph targets information from the mesh to the effect.
  38833. * @param abstractMesh The mesh we are binding the information to render
  38834. * @param effect The effect we are binding the data to
  38835. */
  38836. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38837. var manager = abstractMesh.morphTargetManager;
  38838. if (!abstractMesh || !manager) {
  38839. return;
  38840. }
  38841. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38842. };
  38843. /**
  38844. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38845. * @param defines The generated defines used in the effect
  38846. * @param effect The effect we are binding the data to
  38847. * @param scene The scene we are willing to render with logarithmic scale for
  38848. */
  38849. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38850. if (defines["LOGARITHMICDEPTH"]) {
  38851. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38852. }
  38853. };
  38854. /**
  38855. * Binds the clip plane information from the scene to the effect.
  38856. * @param scene The scene the clip plane information are extracted from
  38857. * @param effect The effect we are binding the data to
  38858. */
  38859. MaterialHelper.BindClipPlane = function (effect, scene) {
  38860. if (scene.clipPlane) {
  38861. var clipPlane = scene.clipPlane;
  38862. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38863. }
  38864. };
  38865. return MaterialHelper;
  38866. }());
  38867. BABYLON.MaterialHelper = MaterialHelper;
  38868. })(BABYLON || (BABYLON = {}));
  38869. //# sourceMappingURL=babylon.materialHelper.js.map
  38870. var BABYLON;
  38871. (function (BABYLON) {
  38872. var PushMaterial = /** @class */ (function (_super) {
  38873. __extends(PushMaterial, _super);
  38874. function PushMaterial(name, scene) {
  38875. var _this = _super.call(this, name, scene) || this;
  38876. _this._normalMatrix = new BABYLON.Matrix();
  38877. _this.storeEffectOnSubMeshes = true;
  38878. return _this;
  38879. }
  38880. PushMaterial.prototype.getEffect = function () {
  38881. return this._activeEffect;
  38882. };
  38883. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38884. if (!mesh) {
  38885. return false;
  38886. }
  38887. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38888. return true;
  38889. }
  38890. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38891. };
  38892. /**
  38893. * Binds the given world matrix to the active effect
  38894. *
  38895. * @param world the matrix to bind
  38896. */
  38897. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38898. this._activeEffect.setMatrix("world", world);
  38899. };
  38900. /**
  38901. * Binds the given normal matrix to the active effect
  38902. *
  38903. * @param normalMatrix the matrix to bind
  38904. */
  38905. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38906. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38907. };
  38908. PushMaterial.prototype.bind = function (world, mesh) {
  38909. if (!mesh) {
  38910. return;
  38911. }
  38912. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38913. };
  38914. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38915. if (effect === void 0) { effect = null; }
  38916. _super.prototype._afterBind.call(this, mesh);
  38917. this.getScene()._cachedEffect = effect;
  38918. };
  38919. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38920. if (visibility === void 0) { visibility = 1; }
  38921. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38922. };
  38923. return PushMaterial;
  38924. }(BABYLON.Material));
  38925. BABYLON.PushMaterial = PushMaterial;
  38926. })(BABYLON || (BABYLON = {}));
  38927. //# sourceMappingURL=babylon.pushMaterial.js.map
  38928. var BABYLON;
  38929. (function (BABYLON) {
  38930. /** @ignore */
  38931. var StandardMaterialDefines = /** @class */ (function (_super) {
  38932. __extends(StandardMaterialDefines, _super);
  38933. function StandardMaterialDefines() {
  38934. var _this = _super.call(this) || this;
  38935. _this.MAINUV1 = false;
  38936. _this.MAINUV2 = false;
  38937. _this.DIFFUSE = false;
  38938. _this.DIFFUSEDIRECTUV = 0;
  38939. _this.AMBIENT = false;
  38940. _this.AMBIENTDIRECTUV = 0;
  38941. _this.OPACITY = false;
  38942. _this.OPACITYDIRECTUV = 0;
  38943. _this.OPACITYRGB = false;
  38944. _this.REFLECTION = false;
  38945. _this.EMISSIVE = false;
  38946. _this.EMISSIVEDIRECTUV = 0;
  38947. _this.SPECULAR = false;
  38948. _this.SPECULARDIRECTUV = 0;
  38949. _this.BUMP = false;
  38950. _this.BUMPDIRECTUV = 0;
  38951. _this.PARALLAX = false;
  38952. _this.PARALLAXOCCLUSION = false;
  38953. _this.SPECULAROVERALPHA = false;
  38954. _this.CLIPPLANE = false;
  38955. _this.ALPHATEST = false;
  38956. _this.DEPTHPREPASS = false;
  38957. _this.ALPHAFROMDIFFUSE = false;
  38958. _this.POINTSIZE = false;
  38959. _this.FOG = false;
  38960. _this.SPECULARTERM = false;
  38961. _this.DIFFUSEFRESNEL = false;
  38962. _this.OPACITYFRESNEL = false;
  38963. _this.REFLECTIONFRESNEL = false;
  38964. _this.REFRACTIONFRESNEL = false;
  38965. _this.EMISSIVEFRESNEL = false;
  38966. _this.FRESNEL = false;
  38967. _this.NORMAL = false;
  38968. _this.UV1 = false;
  38969. _this.UV2 = false;
  38970. _this.VERTEXCOLOR = false;
  38971. _this.VERTEXALPHA = false;
  38972. _this.NUM_BONE_INFLUENCERS = 0;
  38973. _this.BonesPerMesh = 0;
  38974. _this.INSTANCES = false;
  38975. _this.GLOSSINESS = false;
  38976. _this.ROUGHNESS = false;
  38977. _this.EMISSIVEASILLUMINATION = false;
  38978. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38979. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38980. _this.LIGHTMAP = false;
  38981. _this.LIGHTMAPDIRECTUV = 0;
  38982. _this.OBJECTSPACE_NORMALMAP = false;
  38983. _this.USELIGHTMAPASSHADOWMAP = false;
  38984. _this.REFLECTIONMAP_3D = false;
  38985. _this.REFLECTIONMAP_SPHERICAL = false;
  38986. _this.REFLECTIONMAP_PLANAR = false;
  38987. _this.REFLECTIONMAP_CUBIC = false;
  38988. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38989. _this.REFLECTIONMAP_PROJECTION = false;
  38990. _this.REFLECTIONMAP_SKYBOX = false;
  38991. _this.REFLECTIONMAP_EXPLICIT = false;
  38992. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38993. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38994. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38995. _this.INVERTCUBICMAP = false;
  38996. _this.LOGARITHMICDEPTH = false;
  38997. _this.REFRACTION = false;
  38998. _this.REFRACTIONMAP_3D = false;
  38999. _this.REFLECTIONOVERALPHA = false;
  39000. _this.TWOSIDEDLIGHTING = false;
  39001. _this.SHADOWFLOAT = false;
  39002. _this.MORPHTARGETS = false;
  39003. _this.MORPHTARGETS_NORMAL = false;
  39004. _this.MORPHTARGETS_TANGENT = false;
  39005. _this.NUM_MORPH_INFLUENCERS = 0;
  39006. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39007. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39008. _this.IMAGEPROCESSING = false;
  39009. _this.VIGNETTE = false;
  39010. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39011. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39012. _this.TONEMAPPING = false;
  39013. _this.CONTRAST = false;
  39014. _this.COLORCURVES = false;
  39015. _this.COLORGRADING = false;
  39016. _this.COLORGRADING3D = false;
  39017. _this.SAMPLER3DGREENDEPTH = false;
  39018. _this.SAMPLER3DBGRMAP = false;
  39019. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39020. _this.EXPOSURE = false;
  39021. _this.GRAIN = false;
  39022. _this.rebuild();
  39023. return _this;
  39024. }
  39025. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39026. var modes = [
  39027. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39028. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39029. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39030. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39031. ];
  39032. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39033. var mode = modes_1[_i];
  39034. this[mode] = (mode === modeToEnable);
  39035. }
  39036. };
  39037. return StandardMaterialDefines;
  39038. }(BABYLON.MaterialDefines));
  39039. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39040. var StandardMaterial = /** @class */ (function (_super) {
  39041. __extends(StandardMaterial, _super);
  39042. function StandardMaterial(name, scene) {
  39043. var _this = _super.call(this, name, scene) || this;
  39044. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39045. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39046. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39047. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39048. _this.specularPower = 64;
  39049. _this._useAlphaFromDiffuseTexture = false;
  39050. _this._useEmissiveAsIllumination = false;
  39051. _this._linkEmissiveWithDiffuse = false;
  39052. _this._useSpecularOverAlpha = false;
  39053. _this._useReflectionOverAlpha = false;
  39054. _this._disableLighting = false;
  39055. _this._useObjectSpaceNormalMap = false;
  39056. _this._useParallax = false;
  39057. _this._useParallaxOcclusion = false;
  39058. _this.parallaxScaleBias = 0.05;
  39059. _this._roughness = 0;
  39060. _this.indexOfRefraction = 0.98;
  39061. _this.invertRefractionY = true;
  39062. _this._useLightmapAsShadowmap = false;
  39063. _this._useReflectionFresnelFromSpecular = false;
  39064. _this._useGlossinessFromSpecularMapAlpha = false;
  39065. _this._maxSimultaneousLights = 4;
  39066. /**
  39067. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39068. */
  39069. _this._invertNormalMapX = false;
  39070. /**
  39071. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39072. */
  39073. _this._invertNormalMapY = false;
  39074. /**
  39075. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39076. */
  39077. _this._twoSidedLighting = false;
  39078. _this._renderTargets = new BABYLON.SmartArray(16);
  39079. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39080. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39081. // Setup the default processing configuration to the scene.
  39082. _this._attachImageProcessingConfiguration(null);
  39083. _this.getRenderTargetTextures = function () {
  39084. _this._renderTargets.reset();
  39085. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39086. _this._renderTargets.push(_this._reflectionTexture);
  39087. }
  39088. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39089. _this._renderTargets.push(_this._refractionTexture);
  39090. }
  39091. return _this._renderTargets;
  39092. };
  39093. return _this;
  39094. }
  39095. ;
  39096. ;
  39097. ;
  39098. ;
  39099. ;
  39100. ;
  39101. ;
  39102. ;
  39103. ;
  39104. ;
  39105. ;
  39106. ;
  39107. ;
  39108. ;
  39109. ;
  39110. ;
  39111. ;
  39112. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39113. /**
  39114. * Gets the image processing configuration used either in this material.
  39115. */
  39116. get: function () {
  39117. return this._imageProcessingConfiguration;
  39118. },
  39119. /**
  39120. * Sets the Default image processing configuration used either in the this material.
  39121. *
  39122. * If sets to null, the scene one is in use.
  39123. */
  39124. set: function (value) {
  39125. this._attachImageProcessingConfiguration(value);
  39126. // Ensure the effect will be rebuilt.
  39127. this._markAllSubMeshesAsTexturesDirty();
  39128. },
  39129. enumerable: true,
  39130. configurable: true
  39131. });
  39132. /**
  39133. * Attaches a new image processing configuration to the Standard Material.
  39134. * @param configuration
  39135. */
  39136. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39137. var _this = this;
  39138. if (configuration === this._imageProcessingConfiguration) {
  39139. return;
  39140. }
  39141. // Detaches observer.
  39142. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39143. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39144. }
  39145. // Pick the scene configuration if needed.
  39146. if (!configuration) {
  39147. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39148. }
  39149. else {
  39150. this._imageProcessingConfiguration = configuration;
  39151. }
  39152. // Attaches observer.
  39153. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39154. _this._markAllSubMeshesAsImageProcessingDirty();
  39155. });
  39156. };
  39157. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39158. /**
  39159. * Gets wether the color curves effect is enabled.
  39160. */
  39161. get: function () {
  39162. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39163. },
  39164. /**
  39165. * Sets wether the color curves effect is enabled.
  39166. */
  39167. set: function (value) {
  39168. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39169. },
  39170. enumerable: true,
  39171. configurable: true
  39172. });
  39173. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39174. /**
  39175. * Gets wether the color grading effect is enabled.
  39176. */
  39177. get: function () {
  39178. return this.imageProcessingConfiguration.colorGradingEnabled;
  39179. },
  39180. /**
  39181. * Gets wether the color grading effect is enabled.
  39182. */
  39183. set: function (value) {
  39184. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39185. },
  39186. enumerable: true,
  39187. configurable: true
  39188. });
  39189. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39190. /**
  39191. * Gets wether tonemapping is enabled or not.
  39192. */
  39193. get: function () {
  39194. return this._imageProcessingConfiguration.toneMappingEnabled;
  39195. },
  39196. /**
  39197. * Sets wether tonemapping is enabled or not
  39198. */
  39199. set: function (value) {
  39200. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39201. },
  39202. enumerable: true,
  39203. configurable: true
  39204. });
  39205. ;
  39206. ;
  39207. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39208. /**
  39209. * The camera exposure used on this material.
  39210. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39211. * This corresponds to a photographic exposure.
  39212. */
  39213. get: function () {
  39214. return this._imageProcessingConfiguration.exposure;
  39215. },
  39216. /**
  39217. * The camera exposure used on this material.
  39218. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39219. * This corresponds to a photographic exposure.
  39220. */
  39221. set: function (value) {
  39222. this._imageProcessingConfiguration.exposure = value;
  39223. },
  39224. enumerable: true,
  39225. configurable: true
  39226. });
  39227. ;
  39228. ;
  39229. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39230. /**
  39231. * Gets The camera contrast used on this material.
  39232. */
  39233. get: function () {
  39234. return this._imageProcessingConfiguration.contrast;
  39235. },
  39236. /**
  39237. * Sets The camera contrast used on this material.
  39238. */
  39239. set: function (value) {
  39240. this._imageProcessingConfiguration.contrast = value;
  39241. },
  39242. enumerable: true,
  39243. configurable: true
  39244. });
  39245. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39246. /**
  39247. * Gets the Color Grading 2D Lookup Texture.
  39248. */
  39249. get: function () {
  39250. return this._imageProcessingConfiguration.colorGradingTexture;
  39251. },
  39252. /**
  39253. * Sets the Color Grading 2D Lookup Texture.
  39254. */
  39255. set: function (value) {
  39256. this._imageProcessingConfiguration.colorGradingTexture = value;
  39257. },
  39258. enumerable: true,
  39259. configurable: true
  39260. });
  39261. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39262. /**
  39263. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39264. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39265. * 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;
  39266. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39267. */
  39268. get: function () {
  39269. return this._imageProcessingConfiguration.colorCurves;
  39270. },
  39271. /**
  39272. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39273. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39274. * 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;
  39275. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39276. */
  39277. set: function (value) {
  39278. this._imageProcessingConfiguration.colorCurves = value;
  39279. },
  39280. enumerable: true,
  39281. configurable: true
  39282. });
  39283. StandardMaterial.prototype.getClassName = function () {
  39284. return "StandardMaterial";
  39285. };
  39286. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39287. get: function () {
  39288. return this._useLogarithmicDepth;
  39289. },
  39290. set: function (value) {
  39291. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39292. this._markAllSubMeshesAsMiscDirty();
  39293. },
  39294. enumerable: true,
  39295. configurable: true
  39296. });
  39297. StandardMaterial.prototype.needAlphaBlending = function () {
  39298. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39299. };
  39300. StandardMaterial.prototype.needAlphaTesting = function () {
  39301. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39302. };
  39303. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39304. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39305. };
  39306. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39307. return this._diffuseTexture;
  39308. };
  39309. /**
  39310. * Child classes can use it to update shaders
  39311. */
  39312. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39313. if (useInstances === void 0) { useInstances = false; }
  39314. if (subMesh.effect && this.isFrozen) {
  39315. if (this._wasPreviouslyReady && subMesh.effect) {
  39316. return true;
  39317. }
  39318. }
  39319. if (!subMesh._materialDefines) {
  39320. subMesh._materialDefines = new StandardMaterialDefines();
  39321. }
  39322. var scene = this.getScene();
  39323. var defines = subMesh._materialDefines;
  39324. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39325. if (defines._renderId === scene.getRenderId()) {
  39326. return true;
  39327. }
  39328. }
  39329. var engine = scene.getEngine();
  39330. // Lights
  39331. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39332. // Textures
  39333. if (defines._areTexturesDirty) {
  39334. defines._needUVs = false;
  39335. defines.MAINUV1 = false;
  39336. defines.MAINUV2 = false;
  39337. if (scene.texturesEnabled) {
  39338. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39339. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39340. return false;
  39341. }
  39342. else {
  39343. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39344. }
  39345. }
  39346. else {
  39347. defines.DIFFUSE = false;
  39348. }
  39349. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39350. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39351. return false;
  39352. }
  39353. else {
  39354. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39355. }
  39356. }
  39357. else {
  39358. defines.AMBIENT = false;
  39359. }
  39360. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39361. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39362. return false;
  39363. }
  39364. else {
  39365. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39366. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39367. }
  39368. }
  39369. else {
  39370. defines.OPACITY = false;
  39371. }
  39372. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39373. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39374. return false;
  39375. }
  39376. else {
  39377. defines._needNormals = true;
  39378. defines.REFLECTION = true;
  39379. defines.ROUGHNESS = (this._roughness > 0);
  39380. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39381. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39382. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39383. switch (this._reflectionTexture.coordinatesMode) {
  39384. case BABYLON.Texture.CUBIC_MODE:
  39385. case BABYLON.Texture.INVCUBIC_MODE:
  39386. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39387. break;
  39388. case BABYLON.Texture.EXPLICIT_MODE:
  39389. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39390. break;
  39391. case BABYLON.Texture.PLANAR_MODE:
  39392. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39393. break;
  39394. case BABYLON.Texture.PROJECTION_MODE:
  39395. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39396. break;
  39397. case BABYLON.Texture.SKYBOX_MODE:
  39398. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39399. break;
  39400. case BABYLON.Texture.SPHERICAL_MODE:
  39401. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39402. break;
  39403. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39404. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39405. break;
  39406. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39407. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39408. break;
  39409. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39410. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39411. break;
  39412. }
  39413. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39414. }
  39415. }
  39416. else {
  39417. defines.REFLECTION = false;
  39418. }
  39419. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39420. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39421. return false;
  39422. }
  39423. else {
  39424. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39425. }
  39426. }
  39427. else {
  39428. defines.EMISSIVE = false;
  39429. }
  39430. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39431. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39432. return false;
  39433. }
  39434. else {
  39435. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39436. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39437. }
  39438. }
  39439. else {
  39440. defines.LIGHTMAP = false;
  39441. }
  39442. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39443. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39444. return false;
  39445. }
  39446. else {
  39447. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39448. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39449. }
  39450. }
  39451. else {
  39452. defines.SPECULAR = false;
  39453. }
  39454. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39455. // Bump texure can not be not blocking.
  39456. if (!this._bumpTexture.isReady()) {
  39457. return false;
  39458. }
  39459. else {
  39460. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39461. defines.PARALLAX = this._useParallax;
  39462. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39463. }
  39464. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39465. }
  39466. else {
  39467. defines.BUMP = false;
  39468. }
  39469. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39470. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39471. return false;
  39472. }
  39473. else {
  39474. defines._needUVs = true;
  39475. defines.REFRACTION = true;
  39476. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39477. }
  39478. }
  39479. else {
  39480. defines.REFRACTION = false;
  39481. }
  39482. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39483. }
  39484. else {
  39485. defines.DIFFUSE = false;
  39486. defines.AMBIENT = false;
  39487. defines.OPACITY = false;
  39488. defines.REFLECTION = false;
  39489. defines.EMISSIVE = false;
  39490. defines.LIGHTMAP = false;
  39491. defines.BUMP = false;
  39492. defines.REFRACTION = false;
  39493. }
  39494. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39495. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39496. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39497. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39498. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39499. }
  39500. if (defines._areImageProcessingDirty) {
  39501. if (!this._imageProcessingConfiguration.isReady()) {
  39502. return false;
  39503. }
  39504. this._imageProcessingConfiguration.prepareDefines(defines);
  39505. }
  39506. if (defines._areFresnelDirty) {
  39507. if (StandardMaterial.FresnelEnabled) {
  39508. // Fresnel
  39509. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39510. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39511. this._reflectionFresnelParameters) {
  39512. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39513. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39514. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39515. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39516. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39517. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39518. defines._needNormals = true;
  39519. defines.FRESNEL = true;
  39520. }
  39521. }
  39522. else {
  39523. defines.FRESNEL = false;
  39524. }
  39525. }
  39526. // Misc.
  39527. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39528. // Attribs
  39529. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39530. // Values that need to be evaluated on every frame
  39531. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39532. // Get correct effect
  39533. if (defines.isDirty) {
  39534. defines.markAsProcessed();
  39535. scene.resetCachedMaterial();
  39536. // Fallbacks
  39537. var fallbacks = new BABYLON.EffectFallbacks();
  39538. if (defines.REFLECTION) {
  39539. fallbacks.addFallback(0, "REFLECTION");
  39540. }
  39541. if (defines.SPECULAR) {
  39542. fallbacks.addFallback(0, "SPECULAR");
  39543. }
  39544. if (defines.BUMP) {
  39545. fallbacks.addFallback(0, "BUMP");
  39546. }
  39547. if (defines.PARALLAX) {
  39548. fallbacks.addFallback(1, "PARALLAX");
  39549. }
  39550. if (defines.PARALLAXOCCLUSION) {
  39551. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39552. }
  39553. if (defines.SPECULAROVERALPHA) {
  39554. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39555. }
  39556. if (defines.FOG) {
  39557. fallbacks.addFallback(1, "FOG");
  39558. }
  39559. if (defines.POINTSIZE) {
  39560. fallbacks.addFallback(0, "POINTSIZE");
  39561. }
  39562. if (defines.LOGARITHMICDEPTH) {
  39563. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39564. }
  39565. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39566. if (defines.SPECULARTERM) {
  39567. fallbacks.addFallback(0, "SPECULARTERM");
  39568. }
  39569. if (defines.DIFFUSEFRESNEL) {
  39570. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39571. }
  39572. if (defines.OPACITYFRESNEL) {
  39573. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39574. }
  39575. if (defines.REFLECTIONFRESNEL) {
  39576. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39577. }
  39578. if (defines.EMISSIVEFRESNEL) {
  39579. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39580. }
  39581. if (defines.FRESNEL) {
  39582. fallbacks.addFallback(4, "FRESNEL");
  39583. }
  39584. //Attributes
  39585. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39586. if (defines.NORMAL) {
  39587. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39588. }
  39589. if (defines.UV1) {
  39590. attribs.push(BABYLON.VertexBuffer.UVKind);
  39591. }
  39592. if (defines.UV2) {
  39593. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39594. }
  39595. if (defines.VERTEXCOLOR) {
  39596. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39597. }
  39598. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39599. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39600. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39601. var shaderName = "default";
  39602. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39603. "vFogInfos", "vFogColor", "pointSize",
  39604. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39605. "mBones",
  39606. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39607. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39608. "vReflectionPosition", "vReflectionSize",
  39609. "logarithmicDepthConstant", "vTangentSpaceParams"
  39610. ];
  39611. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39612. var uniformBuffers = ["Material", "Scene"];
  39613. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39614. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39615. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39616. uniformsNames: uniforms,
  39617. uniformBuffersNames: uniformBuffers,
  39618. samplers: samplers,
  39619. defines: defines,
  39620. maxSimultaneousLights: this._maxSimultaneousLights
  39621. });
  39622. if (this.customShaderNameResolve) {
  39623. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39624. }
  39625. var join = defines.toString();
  39626. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39627. attributes: attribs,
  39628. uniformsNames: uniforms,
  39629. uniformBuffersNames: uniformBuffers,
  39630. samplers: samplers,
  39631. defines: join,
  39632. fallbacks: fallbacks,
  39633. onCompiled: this.onCompiled,
  39634. onError: this.onError,
  39635. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39636. }, engine), defines);
  39637. this.buildUniformLayout();
  39638. }
  39639. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39640. return false;
  39641. }
  39642. defines._renderId = scene.getRenderId();
  39643. this._wasPreviouslyReady = true;
  39644. return true;
  39645. };
  39646. StandardMaterial.prototype.buildUniformLayout = function () {
  39647. // Order is important !
  39648. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39649. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39650. this._uniformBuffer.addUniform("opacityParts", 4);
  39651. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39652. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39653. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39654. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39655. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39656. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39657. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39658. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39659. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39660. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39661. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39662. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39663. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39664. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39665. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39666. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39667. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39668. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39669. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39670. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39671. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39672. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39673. this._uniformBuffer.addUniform("specularMatrix", 16);
  39674. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39675. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39676. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39677. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39678. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39679. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39680. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39681. this._uniformBuffer.addUniform("pointSize", 1);
  39682. this._uniformBuffer.create();
  39683. };
  39684. StandardMaterial.prototype.unbind = function () {
  39685. if (this._activeEffect) {
  39686. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39687. this._activeEffect.setTexture("reflection2DSampler", null);
  39688. }
  39689. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39690. this._activeEffect.setTexture("refraction2DSampler", null);
  39691. }
  39692. }
  39693. _super.prototype.unbind.call(this);
  39694. };
  39695. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39696. var scene = this.getScene();
  39697. var defines = subMesh._materialDefines;
  39698. if (!defines) {
  39699. return;
  39700. }
  39701. var effect = subMesh.effect;
  39702. if (!effect) {
  39703. return;
  39704. }
  39705. this._activeEffect = effect;
  39706. // Matrices
  39707. this.bindOnlyWorldMatrix(world);
  39708. // Normal Matrix
  39709. if (defines.OBJECTSPACE_NORMALMAP) {
  39710. world.toNormalMatrix(this._normalMatrix);
  39711. this.bindOnlyNormalMatrix(this._normalMatrix);
  39712. }
  39713. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39714. // Bones
  39715. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39716. if (mustRebind) {
  39717. this._uniformBuffer.bindToEffect(effect, "Material");
  39718. this.bindViewProjection(effect);
  39719. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39720. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39721. // Fresnel
  39722. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39723. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39724. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39725. }
  39726. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39727. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39728. }
  39729. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39730. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39731. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39732. }
  39733. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39734. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39735. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39736. }
  39737. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39738. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39739. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39740. }
  39741. }
  39742. // Textures
  39743. if (scene.texturesEnabled) {
  39744. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39745. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39746. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39747. }
  39748. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39749. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39750. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39751. }
  39752. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39753. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39754. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39755. }
  39756. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39757. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39758. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39759. if (this._reflectionTexture.boundingBoxSize) {
  39760. var cubeTexture = this._reflectionTexture;
  39761. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39762. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39763. }
  39764. }
  39765. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39766. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39767. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39768. }
  39769. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39770. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39771. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39772. }
  39773. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39774. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39775. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39776. }
  39777. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39778. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39779. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39780. if (scene._mirroredCameraPosition) {
  39781. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39782. }
  39783. else {
  39784. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39785. }
  39786. }
  39787. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39788. var depth = 1.0;
  39789. if (!this._refractionTexture.isCube) {
  39790. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39791. if (this._refractionTexture.depth) {
  39792. depth = this._refractionTexture.depth;
  39793. }
  39794. }
  39795. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39796. }
  39797. }
  39798. // Point size
  39799. if (this.pointsCloud) {
  39800. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39801. }
  39802. if (defines.SPECULARTERM) {
  39803. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39804. }
  39805. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39806. // Diffuse
  39807. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39808. }
  39809. // Textures
  39810. if (scene.texturesEnabled) {
  39811. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39812. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39813. }
  39814. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39815. effect.setTexture("ambientSampler", this._ambientTexture);
  39816. }
  39817. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39818. effect.setTexture("opacitySampler", this._opacityTexture);
  39819. }
  39820. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39821. if (this._reflectionTexture.isCube) {
  39822. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39823. }
  39824. else {
  39825. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39826. }
  39827. }
  39828. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39829. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39830. }
  39831. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39832. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39833. }
  39834. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39835. effect.setTexture("specularSampler", this._specularTexture);
  39836. }
  39837. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39838. effect.setTexture("bumpSampler", this._bumpTexture);
  39839. }
  39840. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39841. var depth = 1.0;
  39842. if (this._refractionTexture.isCube) {
  39843. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39844. }
  39845. else {
  39846. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39847. }
  39848. }
  39849. }
  39850. // Clip plane
  39851. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39852. // Colors
  39853. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39854. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39855. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39856. }
  39857. if (mustRebind || !this.isFrozen) {
  39858. // Lights
  39859. if (scene.lightsEnabled && !this._disableLighting) {
  39860. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39861. }
  39862. // View
  39863. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39864. this.bindView(effect);
  39865. }
  39866. // Fog
  39867. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39868. // Morph targets
  39869. if (defines.NUM_MORPH_INFLUENCERS) {
  39870. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39871. }
  39872. // Log. depth
  39873. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39874. // image processing
  39875. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39876. this._imageProcessingConfiguration.bind(this._activeEffect);
  39877. }
  39878. }
  39879. this._uniformBuffer.update();
  39880. this._afterBind(mesh, this._activeEffect);
  39881. };
  39882. StandardMaterial.prototype.getAnimatables = function () {
  39883. var results = [];
  39884. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39885. results.push(this._diffuseTexture);
  39886. }
  39887. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39888. results.push(this._ambientTexture);
  39889. }
  39890. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39891. results.push(this._opacityTexture);
  39892. }
  39893. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39894. results.push(this._reflectionTexture);
  39895. }
  39896. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39897. results.push(this._emissiveTexture);
  39898. }
  39899. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39900. results.push(this._specularTexture);
  39901. }
  39902. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39903. results.push(this._bumpTexture);
  39904. }
  39905. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39906. results.push(this._lightmapTexture);
  39907. }
  39908. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39909. results.push(this._refractionTexture);
  39910. }
  39911. return results;
  39912. };
  39913. StandardMaterial.prototype.getActiveTextures = function () {
  39914. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39915. if (this._diffuseTexture) {
  39916. activeTextures.push(this._diffuseTexture);
  39917. }
  39918. if (this._ambientTexture) {
  39919. activeTextures.push(this._ambientTexture);
  39920. }
  39921. if (this._opacityTexture) {
  39922. activeTextures.push(this._opacityTexture);
  39923. }
  39924. if (this._reflectionTexture) {
  39925. activeTextures.push(this._reflectionTexture);
  39926. }
  39927. if (this._emissiveTexture) {
  39928. activeTextures.push(this._emissiveTexture);
  39929. }
  39930. if (this._specularTexture) {
  39931. activeTextures.push(this._specularTexture);
  39932. }
  39933. if (this._bumpTexture) {
  39934. activeTextures.push(this._bumpTexture);
  39935. }
  39936. if (this._lightmapTexture) {
  39937. activeTextures.push(this._lightmapTexture);
  39938. }
  39939. if (this._refractionTexture) {
  39940. activeTextures.push(this._refractionTexture);
  39941. }
  39942. return activeTextures;
  39943. };
  39944. StandardMaterial.prototype.hasTexture = function (texture) {
  39945. if (_super.prototype.hasTexture.call(this, texture)) {
  39946. return true;
  39947. }
  39948. if (this._diffuseTexture === texture) {
  39949. return true;
  39950. }
  39951. if (this._ambientTexture === texture) {
  39952. return true;
  39953. }
  39954. if (this._opacityTexture === texture) {
  39955. return true;
  39956. }
  39957. if (this._reflectionTexture === texture) {
  39958. return true;
  39959. }
  39960. if (this._emissiveTexture === texture) {
  39961. return true;
  39962. }
  39963. if (this._specularTexture === texture) {
  39964. return true;
  39965. }
  39966. if (this._bumpTexture === texture) {
  39967. return true;
  39968. }
  39969. if (this._lightmapTexture === texture) {
  39970. return true;
  39971. }
  39972. if (this._refractionTexture === texture) {
  39973. return true;
  39974. }
  39975. return false;
  39976. };
  39977. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39978. if (forceDisposeTextures) {
  39979. if (this._diffuseTexture) {
  39980. this._diffuseTexture.dispose();
  39981. }
  39982. if (this._ambientTexture) {
  39983. this._ambientTexture.dispose();
  39984. }
  39985. if (this._opacityTexture) {
  39986. this._opacityTexture.dispose();
  39987. }
  39988. if (this._reflectionTexture) {
  39989. this._reflectionTexture.dispose();
  39990. }
  39991. if (this._emissiveTexture) {
  39992. this._emissiveTexture.dispose();
  39993. }
  39994. if (this._specularTexture) {
  39995. this._specularTexture.dispose();
  39996. }
  39997. if (this._bumpTexture) {
  39998. this._bumpTexture.dispose();
  39999. }
  40000. if (this._lightmapTexture) {
  40001. this._lightmapTexture.dispose();
  40002. }
  40003. if (this._refractionTexture) {
  40004. this._refractionTexture.dispose();
  40005. }
  40006. }
  40007. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40008. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40009. }
  40010. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40011. };
  40012. StandardMaterial.prototype.clone = function (name) {
  40013. var _this = this;
  40014. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40015. result.name = name;
  40016. result.id = name;
  40017. return result;
  40018. };
  40019. StandardMaterial.prototype.serialize = function () {
  40020. return BABYLON.SerializationHelper.Serialize(this);
  40021. };
  40022. // Statics
  40023. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40024. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40025. };
  40026. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40027. get: function () {
  40028. return StandardMaterial._DiffuseTextureEnabled;
  40029. },
  40030. set: function (value) {
  40031. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40032. return;
  40033. }
  40034. StandardMaterial._DiffuseTextureEnabled = value;
  40035. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40036. },
  40037. enumerable: true,
  40038. configurable: true
  40039. });
  40040. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40041. get: function () {
  40042. return StandardMaterial._AmbientTextureEnabled;
  40043. },
  40044. set: function (value) {
  40045. if (StandardMaterial._AmbientTextureEnabled === value) {
  40046. return;
  40047. }
  40048. StandardMaterial._AmbientTextureEnabled = value;
  40049. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40050. },
  40051. enumerable: true,
  40052. configurable: true
  40053. });
  40054. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40055. get: function () {
  40056. return StandardMaterial._OpacityTextureEnabled;
  40057. },
  40058. set: function (value) {
  40059. if (StandardMaterial._OpacityTextureEnabled === value) {
  40060. return;
  40061. }
  40062. StandardMaterial._OpacityTextureEnabled = value;
  40063. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40064. },
  40065. enumerable: true,
  40066. configurable: true
  40067. });
  40068. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40069. get: function () {
  40070. return StandardMaterial._ReflectionTextureEnabled;
  40071. },
  40072. set: function (value) {
  40073. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40074. return;
  40075. }
  40076. StandardMaterial._ReflectionTextureEnabled = value;
  40077. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40078. },
  40079. enumerable: true,
  40080. configurable: true
  40081. });
  40082. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40083. get: function () {
  40084. return StandardMaterial._EmissiveTextureEnabled;
  40085. },
  40086. set: function (value) {
  40087. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40088. return;
  40089. }
  40090. StandardMaterial._EmissiveTextureEnabled = value;
  40091. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40092. },
  40093. enumerable: true,
  40094. configurable: true
  40095. });
  40096. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40097. get: function () {
  40098. return StandardMaterial._SpecularTextureEnabled;
  40099. },
  40100. set: function (value) {
  40101. if (StandardMaterial._SpecularTextureEnabled === value) {
  40102. return;
  40103. }
  40104. StandardMaterial._SpecularTextureEnabled = value;
  40105. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40106. },
  40107. enumerable: true,
  40108. configurable: true
  40109. });
  40110. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40111. get: function () {
  40112. return StandardMaterial._BumpTextureEnabled;
  40113. },
  40114. set: function (value) {
  40115. if (StandardMaterial._BumpTextureEnabled === value) {
  40116. return;
  40117. }
  40118. StandardMaterial._BumpTextureEnabled = value;
  40119. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40120. },
  40121. enumerable: true,
  40122. configurable: true
  40123. });
  40124. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40125. get: function () {
  40126. return StandardMaterial._LightmapTextureEnabled;
  40127. },
  40128. set: function (value) {
  40129. if (StandardMaterial._LightmapTextureEnabled === value) {
  40130. return;
  40131. }
  40132. StandardMaterial._LightmapTextureEnabled = value;
  40133. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40134. },
  40135. enumerable: true,
  40136. configurable: true
  40137. });
  40138. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40139. get: function () {
  40140. return StandardMaterial._RefractionTextureEnabled;
  40141. },
  40142. set: function (value) {
  40143. if (StandardMaterial._RefractionTextureEnabled === value) {
  40144. return;
  40145. }
  40146. StandardMaterial._RefractionTextureEnabled = value;
  40147. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40148. },
  40149. enumerable: true,
  40150. configurable: true
  40151. });
  40152. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40153. get: function () {
  40154. return StandardMaterial._ColorGradingTextureEnabled;
  40155. },
  40156. set: function (value) {
  40157. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40158. return;
  40159. }
  40160. StandardMaterial._ColorGradingTextureEnabled = value;
  40161. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40162. },
  40163. enumerable: true,
  40164. configurable: true
  40165. });
  40166. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40167. get: function () {
  40168. return StandardMaterial._FresnelEnabled;
  40169. },
  40170. set: function (value) {
  40171. if (StandardMaterial._FresnelEnabled === value) {
  40172. return;
  40173. }
  40174. StandardMaterial._FresnelEnabled = value;
  40175. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40176. },
  40177. enumerable: true,
  40178. configurable: true
  40179. });
  40180. // Flags used to enable or disable a type of texture for all Standard Materials
  40181. StandardMaterial._DiffuseTextureEnabled = true;
  40182. StandardMaterial._AmbientTextureEnabled = true;
  40183. StandardMaterial._OpacityTextureEnabled = true;
  40184. StandardMaterial._ReflectionTextureEnabled = true;
  40185. StandardMaterial._EmissiveTextureEnabled = true;
  40186. StandardMaterial._SpecularTextureEnabled = true;
  40187. StandardMaterial._BumpTextureEnabled = true;
  40188. StandardMaterial._LightmapTextureEnabled = true;
  40189. StandardMaterial._RefractionTextureEnabled = true;
  40190. StandardMaterial._ColorGradingTextureEnabled = true;
  40191. StandardMaterial._FresnelEnabled = true;
  40192. __decorate([
  40193. BABYLON.serializeAsTexture("diffuseTexture")
  40194. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40195. __decorate([
  40196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40197. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40198. __decorate([
  40199. BABYLON.serializeAsTexture("ambientTexture")
  40200. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40201. __decorate([
  40202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40203. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40204. __decorate([
  40205. BABYLON.serializeAsTexture("opacityTexture")
  40206. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40207. __decorate([
  40208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40209. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40210. __decorate([
  40211. BABYLON.serializeAsTexture("reflectionTexture")
  40212. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40213. __decorate([
  40214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40215. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40216. __decorate([
  40217. BABYLON.serializeAsTexture("emissiveTexture")
  40218. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40219. __decorate([
  40220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40221. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40222. __decorate([
  40223. BABYLON.serializeAsTexture("specularTexture")
  40224. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40225. __decorate([
  40226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40227. ], StandardMaterial.prototype, "specularTexture", void 0);
  40228. __decorate([
  40229. BABYLON.serializeAsTexture("bumpTexture")
  40230. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40231. __decorate([
  40232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40233. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40234. __decorate([
  40235. BABYLON.serializeAsTexture("lightmapTexture")
  40236. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40237. __decorate([
  40238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40239. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40240. __decorate([
  40241. BABYLON.serializeAsTexture("refractionTexture")
  40242. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40243. __decorate([
  40244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40245. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40246. __decorate([
  40247. BABYLON.serializeAsColor3("ambient")
  40248. ], StandardMaterial.prototype, "ambientColor", void 0);
  40249. __decorate([
  40250. BABYLON.serializeAsColor3("diffuse")
  40251. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40252. __decorate([
  40253. BABYLON.serializeAsColor3("specular")
  40254. ], StandardMaterial.prototype, "specularColor", void 0);
  40255. __decorate([
  40256. BABYLON.serializeAsColor3("emissive")
  40257. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40258. __decorate([
  40259. BABYLON.serialize()
  40260. ], StandardMaterial.prototype, "specularPower", void 0);
  40261. __decorate([
  40262. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40263. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40264. __decorate([
  40265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40266. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40267. __decorate([
  40268. BABYLON.serialize("useEmissiveAsIllumination")
  40269. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40270. __decorate([
  40271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40272. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40273. __decorate([
  40274. BABYLON.serialize("linkEmissiveWithDiffuse")
  40275. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40276. __decorate([
  40277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40278. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40279. __decorate([
  40280. BABYLON.serialize("useSpecularOverAlpha")
  40281. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40282. __decorate([
  40283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40284. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40285. __decorate([
  40286. BABYLON.serialize("useReflectionOverAlpha")
  40287. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40288. __decorate([
  40289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40290. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40291. __decorate([
  40292. BABYLON.serialize("disableLighting")
  40293. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40294. __decorate([
  40295. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40296. ], StandardMaterial.prototype, "disableLighting", void 0);
  40297. __decorate([
  40298. BABYLON.serialize("useObjectSpaceNormalMap")
  40299. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40300. __decorate([
  40301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40302. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40303. __decorate([
  40304. BABYLON.serialize("useParallax")
  40305. ], StandardMaterial.prototype, "_useParallax", void 0);
  40306. __decorate([
  40307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40308. ], StandardMaterial.prototype, "useParallax", void 0);
  40309. __decorate([
  40310. BABYLON.serialize("useParallaxOcclusion")
  40311. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40312. __decorate([
  40313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40314. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40315. __decorate([
  40316. BABYLON.serialize()
  40317. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40318. __decorate([
  40319. BABYLON.serialize("roughness")
  40320. ], StandardMaterial.prototype, "_roughness", void 0);
  40321. __decorate([
  40322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40323. ], StandardMaterial.prototype, "roughness", void 0);
  40324. __decorate([
  40325. BABYLON.serialize()
  40326. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40327. __decorate([
  40328. BABYLON.serialize()
  40329. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40330. __decorate([
  40331. BABYLON.serialize("useLightmapAsShadowmap")
  40332. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40333. __decorate([
  40334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40335. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40336. __decorate([
  40337. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40338. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40339. __decorate([
  40340. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40341. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40342. __decorate([
  40343. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40344. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40345. __decorate([
  40346. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40347. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40348. __decorate([
  40349. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40350. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40351. __decorate([
  40352. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40353. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40354. __decorate([
  40355. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40356. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40357. __decorate([
  40358. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40359. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40360. __decorate([
  40361. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40362. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40363. __decorate([
  40364. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40365. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40366. __decorate([
  40367. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40368. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40369. __decorate([
  40370. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40371. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40372. __decorate([
  40373. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40374. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40375. __decorate([
  40376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40377. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40378. __decorate([
  40379. BABYLON.serialize("maxSimultaneousLights")
  40380. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40381. __decorate([
  40382. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40383. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40384. __decorate([
  40385. BABYLON.serialize("invertNormalMapX")
  40386. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40387. __decorate([
  40388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40389. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40390. __decorate([
  40391. BABYLON.serialize("invertNormalMapY")
  40392. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40393. __decorate([
  40394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40395. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40396. __decorate([
  40397. BABYLON.serialize("twoSidedLighting")
  40398. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40399. __decorate([
  40400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40401. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40402. __decorate([
  40403. BABYLON.serialize()
  40404. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40405. return StandardMaterial;
  40406. }(BABYLON.PushMaterial));
  40407. BABYLON.StandardMaterial = StandardMaterial;
  40408. })(BABYLON || (BABYLON = {}));
  40409. //# sourceMappingURL=babylon.standardMaterial.js.map
  40410. var BABYLON;
  40411. (function (BABYLON) {
  40412. /**
  40413. * Manages the defines for the PBR Material.
  40414. */
  40415. var PBRMaterialDefines = /** @class */ (function (_super) {
  40416. __extends(PBRMaterialDefines, _super);
  40417. /**
  40418. * Initializes the PBR Material defines.
  40419. */
  40420. function PBRMaterialDefines() {
  40421. var _this = _super.call(this) || this;
  40422. _this.PBR = true;
  40423. _this.MAINUV1 = false;
  40424. _this.MAINUV2 = false;
  40425. _this.UV1 = false;
  40426. _this.UV2 = false;
  40427. _this.ALBEDO = false;
  40428. _this.ALBEDODIRECTUV = 0;
  40429. _this.VERTEXCOLOR = false;
  40430. _this.AMBIENT = false;
  40431. _this.AMBIENTDIRECTUV = 0;
  40432. _this.AMBIENTINGRAYSCALE = false;
  40433. _this.OPACITY = false;
  40434. _this.VERTEXALPHA = false;
  40435. _this.OPACITYDIRECTUV = 0;
  40436. _this.OPACITYRGB = false;
  40437. _this.ALPHATEST = false;
  40438. _this.DEPTHPREPASS = false;
  40439. _this.ALPHABLEND = false;
  40440. _this.ALPHAFROMALBEDO = false;
  40441. _this.ALPHATESTVALUE = 0.5;
  40442. _this.SPECULAROVERALPHA = false;
  40443. _this.RADIANCEOVERALPHA = false;
  40444. _this.ALPHAFRESNEL = false;
  40445. _this.LINEARALPHAFRESNEL = false;
  40446. _this.PREMULTIPLYALPHA = false;
  40447. _this.EMISSIVE = false;
  40448. _this.EMISSIVEDIRECTUV = 0;
  40449. _this.REFLECTIVITY = false;
  40450. _this.REFLECTIVITYDIRECTUV = 0;
  40451. _this.SPECULARTERM = false;
  40452. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40453. _this.MICROSURFACEAUTOMATIC = false;
  40454. _this.LODBASEDMICROSFURACE = false;
  40455. _this.MICROSURFACEMAP = false;
  40456. _this.MICROSURFACEMAPDIRECTUV = 0;
  40457. _this.METALLICWORKFLOW = false;
  40458. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40459. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40460. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40461. _this.AOSTOREINMETALMAPRED = false;
  40462. _this.ENVIRONMENTBRDF = false;
  40463. _this.NORMAL = false;
  40464. _this.TANGENT = false;
  40465. _this.BUMP = false;
  40466. _this.BUMPDIRECTUV = 0;
  40467. _this.OBJECTSPACE_NORMALMAP = false;
  40468. _this.PARALLAX = false;
  40469. _this.PARALLAXOCCLUSION = false;
  40470. _this.NORMALXYSCALE = true;
  40471. _this.LIGHTMAP = false;
  40472. _this.LIGHTMAPDIRECTUV = 0;
  40473. _this.USELIGHTMAPASSHADOWMAP = false;
  40474. _this.REFLECTION = false;
  40475. _this.REFLECTIONMAP_3D = false;
  40476. _this.REFLECTIONMAP_SPHERICAL = false;
  40477. _this.REFLECTIONMAP_PLANAR = false;
  40478. _this.REFLECTIONMAP_CUBIC = false;
  40479. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40480. _this.REFLECTIONMAP_PROJECTION = false;
  40481. _this.REFLECTIONMAP_SKYBOX = false;
  40482. _this.REFLECTIONMAP_EXPLICIT = false;
  40483. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40484. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40485. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40486. _this.INVERTCUBICMAP = false;
  40487. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40488. _this.USESPHERICALINVERTEX = false;
  40489. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40490. _this.LODINREFLECTIONALPHA = false;
  40491. _this.GAMMAREFLECTION = false;
  40492. _this.RADIANCEOCCLUSION = false;
  40493. _this.HORIZONOCCLUSION = false;
  40494. _this.REFRACTION = false;
  40495. _this.REFRACTIONMAP_3D = false;
  40496. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40497. _this.LODINREFRACTIONALPHA = false;
  40498. _this.GAMMAREFRACTION = false;
  40499. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40500. _this.INSTANCES = false;
  40501. _this.NUM_BONE_INFLUENCERS = 0;
  40502. _this.BonesPerMesh = 0;
  40503. _this.NONUNIFORMSCALING = false;
  40504. _this.MORPHTARGETS = false;
  40505. _this.MORPHTARGETS_NORMAL = false;
  40506. _this.MORPHTARGETS_TANGENT = false;
  40507. _this.NUM_MORPH_INFLUENCERS = 0;
  40508. _this.IMAGEPROCESSING = false;
  40509. _this.VIGNETTE = false;
  40510. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40511. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40512. _this.TONEMAPPING = false;
  40513. _this.CONTRAST = false;
  40514. _this.COLORCURVES = false;
  40515. _this.COLORGRADING = false;
  40516. _this.COLORGRADING3D = false;
  40517. _this.SAMPLER3DGREENDEPTH = false;
  40518. _this.SAMPLER3DBGRMAP = false;
  40519. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40520. _this.EXPOSURE = false;
  40521. _this.GRAIN = false;
  40522. _this.USEPHYSICALLIGHTFALLOFF = false;
  40523. _this.TWOSIDEDLIGHTING = false;
  40524. _this.SHADOWFLOAT = false;
  40525. _this.CLIPPLANE = false;
  40526. _this.POINTSIZE = false;
  40527. _this.FOG = false;
  40528. _this.LOGARITHMICDEPTH = false;
  40529. _this.FORCENORMALFORWARD = false;
  40530. _this.rebuild();
  40531. return _this;
  40532. }
  40533. /**
  40534. * Resets the PBR Material defines.
  40535. */
  40536. PBRMaterialDefines.prototype.reset = function () {
  40537. _super.prototype.reset.call(this);
  40538. this.ALPHATESTVALUE = 0.5;
  40539. this.PBR = true;
  40540. };
  40541. return PBRMaterialDefines;
  40542. }(BABYLON.MaterialDefines));
  40543. /**
  40544. * The Physically based material base class of BJS.
  40545. *
  40546. * This offers the main features of a standard PBR material.
  40547. * For more information, please refer to the documentation :
  40548. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40549. */
  40550. var PBRBaseMaterial = /** @class */ (function (_super) {
  40551. __extends(PBRBaseMaterial, _super);
  40552. /**
  40553. * Instantiates a new PBRMaterial instance.
  40554. *
  40555. * @param name The material name
  40556. * @param scene The scene the material will be use in.
  40557. */
  40558. function PBRBaseMaterial(name, scene) {
  40559. var _this = _super.call(this, name, scene) || this;
  40560. /**
  40561. * Intensity of the direct lights e.g. the four lights available in your scene.
  40562. * This impacts both the direct diffuse and specular highlights.
  40563. */
  40564. _this._directIntensity = 1.0;
  40565. /**
  40566. * Intensity of the emissive part of the material.
  40567. * This helps controlling the emissive effect without modifying the emissive color.
  40568. */
  40569. _this._emissiveIntensity = 1.0;
  40570. /**
  40571. * Intensity of the environment e.g. how much the environment will light the object
  40572. * either through harmonics for rough material or through the refelction for shiny ones.
  40573. */
  40574. _this._environmentIntensity = 1.0;
  40575. /**
  40576. * This is a special control allowing the reduction of the specular highlights coming from the
  40577. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40578. */
  40579. _this._specularIntensity = 1.0;
  40580. /**
  40581. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40582. */
  40583. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40584. /**
  40585. * Debug Control allowing disabling the bump map on this material.
  40586. */
  40587. _this._disableBumpMap = false;
  40588. /**
  40589. * AKA Occlusion Texture Intensity in other nomenclature.
  40590. */
  40591. _this._ambientTextureStrength = 1.0;
  40592. /**
  40593. * The color of a material in ambient lighting.
  40594. */
  40595. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40596. /**
  40597. * AKA Diffuse Color in other nomenclature.
  40598. */
  40599. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40600. /**
  40601. * AKA Specular Color in other nomenclature.
  40602. */
  40603. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40604. /**
  40605. * The color applied when light is reflected from a material.
  40606. */
  40607. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40608. /**
  40609. * The color applied when light is emitted from a material.
  40610. */
  40611. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40612. /**
  40613. * AKA Glossiness in other nomenclature.
  40614. */
  40615. _this._microSurface = 0.9;
  40616. /**
  40617. * source material index of refraction (IOR)' / 'destination material IOR.
  40618. */
  40619. _this._indexOfRefraction = 0.66;
  40620. /**
  40621. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40622. */
  40623. _this._invertRefractionY = false;
  40624. /**
  40625. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40626. * Materials half opaque for instance using refraction could benefit from this control.
  40627. */
  40628. _this._linkRefractionWithTransparency = false;
  40629. /**
  40630. * Specifies that the material will use the light map as a show map.
  40631. */
  40632. _this._useLightmapAsShadowmap = false;
  40633. /**
  40634. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40635. * makes the reflect vector face the model (under horizon).
  40636. */
  40637. _this._useHorizonOcclusion = true;
  40638. /**
  40639. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40640. * too much the area relying on ambient texture to define their ambient occlusion.
  40641. */
  40642. _this._useRadianceOcclusion = true;
  40643. /**
  40644. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40645. */
  40646. _this._useAlphaFromAlbedoTexture = false;
  40647. /**
  40648. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40649. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40650. */
  40651. _this._useSpecularOverAlpha = true;
  40652. /**
  40653. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40654. */
  40655. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40656. /**
  40657. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40658. */
  40659. _this._useRoughnessFromMetallicTextureAlpha = true;
  40660. /**
  40661. * Specifies if the metallic texture contains the roughness information in its green channel.
  40662. */
  40663. _this._useRoughnessFromMetallicTextureGreen = false;
  40664. /**
  40665. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40666. */
  40667. _this._useMetallnessFromMetallicTextureBlue = false;
  40668. /**
  40669. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40670. */
  40671. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40672. /**
  40673. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40674. */
  40675. _this._useAmbientInGrayScale = false;
  40676. /**
  40677. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40678. * The material will try to infer what glossiness each pixel should be.
  40679. */
  40680. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40681. /**
  40682. * BJS is using an harcoded light falloff based on a manually sets up range.
  40683. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40684. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40685. */
  40686. _this._usePhysicalLightFalloff = true;
  40687. /**
  40688. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40689. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40690. */
  40691. _this._useRadianceOverAlpha = true;
  40692. /**
  40693. * Allows using an object space normal map (instead of tangent space).
  40694. */
  40695. _this._useObjectSpaceNormalMap = false;
  40696. /**
  40697. * Allows using the bump map in parallax mode.
  40698. */
  40699. _this._useParallax = false;
  40700. /**
  40701. * Allows using the bump map in parallax occlusion mode.
  40702. */
  40703. _this._useParallaxOcclusion = false;
  40704. /**
  40705. * Controls the scale bias of the parallax mode.
  40706. */
  40707. _this._parallaxScaleBias = 0.05;
  40708. /**
  40709. * If sets to true, disables all the lights affecting the material.
  40710. */
  40711. _this._disableLighting = false;
  40712. /**
  40713. * Number of Simultaneous lights allowed on the material.
  40714. */
  40715. _this._maxSimultaneousLights = 4;
  40716. /**
  40717. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40718. */
  40719. _this._invertNormalMapX = false;
  40720. /**
  40721. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40722. */
  40723. _this._invertNormalMapY = false;
  40724. /**
  40725. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40726. */
  40727. _this._twoSidedLighting = false;
  40728. /**
  40729. * Defines the alpha limits in alpha test mode.
  40730. */
  40731. _this._alphaCutOff = 0.4;
  40732. /**
  40733. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40734. */
  40735. _this._forceAlphaTest = false;
  40736. /**
  40737. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40738. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40739. */
  40740. _this._useAlphaFresnel = false;
  40741. /**
  40742. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40743. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40744. */
  40745. _this._useLinearAlphaFresnel = false;
  40746. /**
  40747. * The transparency mode of the material.
  40748. */
  40749. _this._transparencyMode = null;
  40750. /**
  40751. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40752. * from cos thetav and roughness:
  40753. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40754. */
  40755. _this._environmentBRDFTexture = null;
  40756. /**
  40757. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40758. */
  40759. _this._forceIrradianceInFragment = false;
  40760. /**
  40761. * Force normal to face away from face.
  40762. */
  40763. _this._forceNormalForward = false;
  40764. /**
  40765. * Stores the available render targets.
  40766. */
  40767. _this._renderTargets = new BABYLON.SmartArray(16);
  40768. /**
  40769. * Sets the global ambient color for the material used in lighting calculations.
  40770. */
  40771. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40772. // Setup the default processing configuration to the scene.
  40773. _this._attachImageProcessingConfiguration(null);
  40774. _this.getRenderTargetTextures = function () {
  40775. _this._renderTargets.reset();
  40776. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40777. _this._renderTargets.push(_this._reflectionTexture);
  40778. }
  40779. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40780. _this._renderTargets.push(_this._refractionTexture);
  40781. }
  40782. return _this._renderTargets;
  40783. };
  40784. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40785. return _this;
  40786. }
  40787. /**
  40788. * Attaches a new image processing configuration to the PBR Material.
  40789. * @param configuration
  40790. */
  40791. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40792. var _this = this;
  40793. if (configuration === this._imageProcessingConfiguration) {
  40794. return;
  40795. }
  40796. // Detaches observer.
  40797. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40798. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40799. }
  40800. // Pick the scene configuration if needed.
  40801. if (!configuration) {
  40802. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40803. }
  40804. else {
  40805. this._imageProcessingConfiguration = configuration;
  40806. }
  40807. // Attaches observer.
  40808. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40809. _this._markAllSubMeshesAsImageProcessingDirty();
  40810. });
  40811. };
  40812. /**
  40813. * Gets the name of the material class.
  40814. */
  40815. PBRBaseMaterial.prototype.getClassName = function () {
  40816. return "PBRBaseMaterial";
  40817. };
  40818. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40819. /**
  40820. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40821. */
  40822. get: function () {
  40823. return this._useLogarithmicDepth;
  40824. },
  40825. /**
  40826. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40827. */
  40828. set: function (value) {
  40829. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40830. },
  40831. enumerable: true,
  40832. configurable: true
  40833. });
  40834. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40835. /**
  40836. * Gets the current transparency mode.
  40837. */
  40838. get: function () {
  40839. return this._transparencyMode;
  40840. },
  40841. /**
  40842. * Sets the transparency mode of the material.
  40843. */
  40844. set: function (value) {
  40845. if (this._transparencyMode === value) {
  40846. return;
  40847. }
  40848. this._transparencyMode = value;
  40849. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40850. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40851. },
  40852. enumerable: true,
  40853. configurable: true
  40854. });
  40855. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40856. /**
  40857. * Returns true if alpha blending should be disabled.
  40858. */
  40859. get: function () {
  40860. return (this._linkRefractionWithTransparency ||
  40861. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40862. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40863. },
  40864. enumerable: true,
  40865. configurable: true
  40866. });
  40867. /**
  40868. * Specifies whether or not this material should be rendered in alpha blend mode.
  40869. */
  40870. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40871. if (this._disableAlphaBlending) {
  40872. return false;
  40873. }
  40874. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40875. };
  40876. /**
  40877. * Specifies if the mesh will require alpha blending.
  40878. * @param mesh - BJS mesh.
  40879. */
  40880. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40881. if (this._disableAlphaBlending) {
  40882. return false;
  40883. }
  40884. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40885. };
  40886. /**
  40887. * Specifies whether or not this material should be rendered in alpha test mode.
  40888. */
  40889. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40890. if (this._forceAlphaTest) {
  40891. return true;
  40892. }
  40893. if (this._linkRefractionWithTransparency) {
  40894. return false;
  40895. }
  40896. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40897. };
  40898. /**
  40899. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40900. */
  40901. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40902. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40903. };
  40904. /**
  40905. * Gets the texture used for the alpha test.
  40906. */
  40907. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40908. return this._albedoTexture;
  40909. };
  40910. /**
  40911. * Specifies that the submesh is ready to be used.
  40912. * @param mesh - BJS mesh.
  40913. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40914. * @param useInstances - Specifies that instances should be used.
  40915. * @returns - boolean indicating that the submesh is ready or not.
  40916. */
  40917. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40918. if (subMesh.effect && this.isFrozen) {
  40919. if (this._wasPreviouslyReady) {
  40920. return true;
  40921. }
  40922. }
  40923. if (!subMesh._materialDefines) {
  40924. subMesh._materialDefines = new PBRMaterialDefines();
  40925. }
  40926. var defines = subMesh._materialDefines;
  40927. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40928. if (defines._renderId === this.getScene().getRenderId()) {
  40929. return true;
  40930. }
  40931. }
  40932. var scene = this.getScene();
  40933. var engine = scene.getEngine();
  40934. if (defines._areTexturesDirty) {
  40935. if (scene.texturesEnabled) {
  40936. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40937. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40938. return false;
  40939. }
  40940. }
  40941. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40942. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40943. return false;
  40944. }
  40945. }
  40946. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40947. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40948. return false;
  40949. }
  40950. }
  40951. var reflectionTexture = this._getReflectionTexture();
  40952. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40953. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40954. return false;
  40955. }
  40956. }
  40957. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40958. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40959. return false;
  40960. }
  40961. }
  40962. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40963. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40964. return false;
  40965. }
  40966. }
  40967. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40968. if (this._metallicTexture) {
  40969. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40970. return false;
  40971. }
  40972. }
  40973. else if (this._reflectivityTexture) {
  40974. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40975. return false;
  40976. }
  40977. }
  40978. if (this._microSurfaceTexture) {
  40979. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40980. return false;
  40981. }
  40982. }
  40983. }
  40984. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40985. // Bump texture cannot be not blocking.
  40986. if (!this._bumpTexture.isReady()) {
  40987. return false;
  40988. }
  40989. }
  40990. var refractionTexture = this._getRefractionTexture();
  40991. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40992. if (!refractionTexture.isReadyOrNotBlocking()) {
  40993. return false;
  40994. }
  40995. }
  40996. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40997. // This is blocking.
  40998. if (!this._environmentBRDFTexture.isReady()) {
  40999. return false;
  41000. }
  41001. }
  41002. }
  41003. }
  41004. if (defines._areImageProcessingDirty) {
  41005. if (!this._imageProcessingConfiguration.isReady()) {
  41006. return false;
  41007. }
  41008. }
  41009. if (!engine.getCaps().standardDerivatives) {
  41010. var bufferMesh = null;
  41011. if (mesh.getClassName() === "InstancedMesh") {
  41012. bufferMesh = mesh.sourceMesh;
  41013. }
  41014. else if (mesh.getClassName() === "Mesh") {
  41015. bufferMesh = mesh;
  41016. }
  41017. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41018. bufferMesh.createNormals(true);
  41019. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  41020. }
  41021. }
  41022. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41023. if (effect) {
  41024. scene.resetCachedMaterial();
  41025. subMesh.setEffect(effect, defines);
  41026. this.buildUniformLayout();
  41027. }
  41028. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41029. return false;
  41030. }
  41031. defines._renderId = scene.getRenderId();
  41032. this._wasPreviouslyReady = true;
  41033. return true;
  41034. };
  41035. /**
  41036. * Specifies if the material uses metallic roughness workflow.
  41037. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41038. */
  41039. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41040. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41041. return true;
  41042. }
  41043. return false;
  41044. };
  41045. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41046. if (onCompiled === void 0) { onCompiled = null; }
  41047. if (onError === void 0) { onError = null; }
  41048. if (useInstances === void 0) { useInstances = null; }
  41049. if (useClipPlane === void 0) { useClipPlane = null; }
  41050. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41051. if (!defines.isDirty) {
  41052. return null;
  41053. }
  41054. defines.markAsProcessed();
  41055. var scene = this.getScene();
  41056. var engine = scene.getEngine();
  41057. // Fallbacks
  41058. var fallbacks = new BABYLON.EffectFallbacks();
  41059. var fallbackRank = 0;
  41060. if (defines.USESPHERICALINVERTEX) {
  41061. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41062. }
  41063. if (defines.FOG) {
  41064. fallbacks.addFallback(fallbackRank, "FOG");
  41065. }
  41066. if (defines.POINTSIZE) {
  41067. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41068. }
  41069. if (defines.LOGARITHMICDEPTH) {
  41070. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41071. }
  41072. if (defines.PARALLAX) {
  41073. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41074. }
  41075. if (defines.PARALLAXOCCLUSION) {
  41076. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41077. }
  41078. if (defines.ENVIRONMENTBRDF) {
  41079. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41080. }
  41081. if (defines.TANGENT) {
  41082. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41083. }
  41084. if (defines.BUMP) {
  41085. fallbacks.addFallback(fallbackRank++, "BUMP");
  41086. }
  41087. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41088. if (defines.SPECULARTERM) {
  41089. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41090. }
  41091. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41092. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41093. }
  41094. if (defines.LIGHTMAP) {
  41095. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41096. }
  41097. if (defines.NORMAL) {
  41098. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41099. }
  41100. if (defines.AMBIENT) {
  41101. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41102. }
  41103. if (defines.EMISSIVE) {
  41104. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41105. }
  41106. if (defines.VERTEXCOLOR) {
  41107. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41108. }
  41109. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41110. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41111. }
  41112. if (defines.MORPHTARGETS) {
  41113. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41114. }
  41115. //Attributes
  41116. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41117. if (defines.NORMAL) {
  41118. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41119. }
  41120. if (defines.TANGENT) {
  41121. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41122. }
  41123. if (defines.UV1) {
  41124. attribs.push(BABYLON.VertexBuffer.UVKind);
  41125. }
  41126. if (defines.UV2) {
  41127. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41128. }
  41129. if (defines.VERTEXCOLOR) {
  41130. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41131. }
  41132. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41133. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41134. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41135. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41136. "vFogInfos", "vFogColor", "pointSize",
  41137. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41138. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41139. "mBones",
  41140. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41141. "vLightingIntensity",
  41142. "logarithmicDepthConstant",
  41143. "vSphericalX", "vSphericalY", "vSphericalZ",
  41144. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41145. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41146. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41147. "vTangentSpaceParams"
  41148. ];
  41149. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41150. "bumpSampler", "lightmapSampler", "opacitySampler",
  41151. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41152. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41153. "microSurfaceSampler", "environmentBrdfSampler"];
  41154. var uniformBuffers = ["Material", "Scene"];
  41155. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41156. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41157. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41158. uniformsNames: uniforms,
  41159. uniformBuffersNames: uniformBuffers,
  41160. samplers: samplers,
  41161. defines: defines,
  41162. maxSimultaneousLights: this._maxSimultaneousLights
  41163. });
  41164. var join = defines.toString();
  41165. return engine.createEffect("pbr", {
  41166. attributes: attribs,
  41167. uniformsNames: uniforms,
  41168. uniformBuffersNames: uniformBuffers,
  41169. samplers: samplers,
  41170. defines: join,
  41171. fallbacks: fallbacks,
  41172. onCompiled: onCompiled,
  41173. onError: onError,
  41174. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41175. }, engine);
  41176. };
  41177. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41178. if (useInstances === void 0) { useInstances = null; }
  41179. if (useClipPlane === void 0) { useClipPlane = null; }
  41180. var scene = this.getScene();
  41181. var engine = scene.getEngine();
  41182. // Lights
  41183. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41184. defines._needNormals = true;
  41185. // Textures
  41186. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41187. if (defines._areTexturesDirty) {
  41188. defines._needUVs = false;
  41189. if (scene.texturesEnabled) {
  41190. if (scene.getEngine().getCaps().textureLOD) {
  41191. defines.LODBASEDMICROSFURACE = true;
  41192. }
  41193. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41194. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41195. }
  41196. else {
  41197. defines.ALBEDO = false;
  41198. }
  41199. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41200. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41201. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41202. }
  41203. else {
  41204. defines.AMBIENT = false;
  41205. }
  41206. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41207. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41208. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41209. }
  41210. else {
  41211. defines.OPACITY = false;
  41212. }
  41213. var reflectionTexture = this._getReflectionTexture();
  41214. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41215. defines.REFLECTION = true;
  41216. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41217. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41218. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41219. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41220. defines.INVERTCUBICMAP = true;
  41221. }
  41222. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41223. switch (reflectionTexture.coordinatesMode) {
  41224. case BABYLON.Texture.CUBIC_MODE:
  41225. case BABYLON.Texture.INVCUBIC_MODE:
  41226. defines.REFLECTIONMAP_CUBIC = true;
  41227. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41228. break;
  41229. case BABYLON.Texture.EXPLICIT_MODE:
  41230. defines.REFLECTIONMAP_EXPLICIT = true;
  41231. break;
  41232. case BABYLON.Texture.PLANAR_MODE:
  41233. defines.REFLECTIONMAP_PLANAR = true;
  41234. break;
  41235. case BABYLON.Texture.PROJECTION_MODE:
  41236. defines.REFLECTIONMAP_PROJECTION = true;
  41237. break;
  41238. case BABYLON.Texture.SKYBOX_MODE:
  41239. defines.REFLECTIONMAP_SKYBOX = true;
  41240. break;
  41241. case BABYLON.Texture.SPHERICAL_MODE:
  41242. defines.REFLECTIONMAP_SPHERICAL = true;
  41243. break;
  41244. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41245. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41246. break;
  41247. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41248. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41249. break;
  41250. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41251. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41252. break;
  41253. }
  41254. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41255. if (reflectionTexture.sphericalPolynomial) {
  41256. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41257. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41258. defines.USESPHERICALINVERTEX = false;
  41259. }
  41260. else {
  41261. defines.USESPHERICALINVERTEX = true;
  41262. }
  41263. }
  41264. }
  41265. }
  41266. else {
  41267. defines.REFLECTION = false;
  41268. defines.REFLECTIONMAP_3D = false;
  41269. defines.REFLECTIONMAP_SPHERICAL = false;
  41270. defines.REFLECTIONMAP_PLANAR = false;
  41271. defines.REFLECTIONMAP_CUBIC = false;
  41272. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41273. defines.REFLECTIONMAP_PROJECTION = false;
  41274. defines.REFLECTIONMAP_SKYBOX = false;
  41275. defines.REFLECTIONMAP_EXPLICIT = false;
  41276. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41277. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41278. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41279. defines.INVERTCUBICMAP = false;
  41280. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41281. defines.USESPHERICALINVERTEX = false;
  41282. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41283. defines.LODINREFLECTIONALPHA = false;
  41284. defines.GAMMAREFLECTION = false;
  41285. }
  41286. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41287. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41288. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41289. }
  41290. else {
  41291. defines.LIGHTMAP = false;
  41292. }
  41293. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41294. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41295. }
  41296. else {
  41297. defines.EMISSIVE = false;
  41298. }
  41299. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41300. if (this._metallicTexture) {
  41301. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41302. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41303. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41304. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41305. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41306. }
  41307. else if (this._reflectivityTexture) {
  41308. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41309. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41310. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41311. }
  41312. else {
  41313. defines.REFLECTIVITY = false;
  41314. }
  41315. if (this._microSurfaceTexture) {
  41316. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41317. }
  41318. else {
  41319. defines.MICROSURFACEMAP = false;
  41320. }
  41321. }
  41322. else {
  41323. defines.REFLECTIVITY = false;
  41324. defines.MICROSURFACEMAP = false;
  41325. }
  41326. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41327. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41328. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41329. defines.PARALLAX = true;
  41330. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41331. }
  41332. else {
  41333. defines.PARALLAX = false;
  41334. }
  41335. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41336. }
  41337. else {
  41338. defines.BUMP = false;
  41339. }
  41340. var refractionTexture = this._getRefractionTexture();
  41341. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41342. defines.REFRACTION = true;
  41343. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41344. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41345. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41346. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41347. if (this._linkRefractionWithTransparency) {
  41348. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41349. }
  41350. }
  41351. else {
  41352. defines.REFRACTION = false;
  41353. }
  41354. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41355. defines.ENVIRONMENTBRDF = true;
  41356. }
  41357. else {
  41358. defines.ENVIRONMENTBRDF = false;
  41359. }
  41360. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41361. defines.ALPHAFROMALBEDO = true;
  41362. }
  41363. else {
  41364. defines.ALPHAFROMALBEDO = false;
  41365. }
  41366. }
  41367. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41368. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41369. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41370. if (!this.backFaceCulling && this._twoSidedLighting) {
  41371. defines.TWOSIDEDLIGHTING = true;
  41372. }
  41373. else {
  41374. defines.TWOSIDEDLIGHTING = false;
  41375. }
  41376. defines.ALPHATESTVALUE = this._alphaCutOff;
  41377. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41378. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41379. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41380. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41381. }
  41382. if (defines._areImageProcessingDirty) {
  41383. this._imageProcessingConfiguration.prepareDefines(defines);
  41384. }
  41385. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41386. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41387. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41388. // Misc.
  41389. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41390. // Values that need to be evaluated on every frame
  41391. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41392. // Attribs
  41393. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41394. };
  41395. /**
  41396. * Force shader compilation
  41397. */
  41398. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41399. var _this = this;
  41400. var localOptions = __assign({ clipPlane: false }, options);
  41401. var defines = new PBRMaterialDefines();
  41402. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41403. if (effect.isReady()) {
  41404. if (onCompiled) {
  41405. onCompiled(this);
  41406. }
  41407. }
  41408. else {
  41409. effect.onCompileObservable.add(function () {
  41410. if (onCompiled) {
  41411. onCompiled(_this);
  41412. }
  41413. });
  41414. }
  41415. };
  41416. /**
  41417. * Initializes the uniform buffer layout for the shader.
  41418. */
  41419. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41420. // Order is important !
  41421. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41422. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41423. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41424. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41425. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41426. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41427. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41428. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41429. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41430. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41431. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41432. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41433. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41434. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41435. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41436. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41437. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41438. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41439. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41440. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41441. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41442. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41443. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41444. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41445. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41446. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41447. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41448. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41449. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41450. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41451. this._uniformBuffer.addUniform("pointSize", 1);
  41452. this._uniformBuffer.create();
  41453. };
  41454. /**
  41455. * Unbinds the textures.
  41456. */
  41457. PBRBaseMaterial.prototype.unbind = function () {
  41458. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41459. this._uniformBuffer.setTexture("reflectionSampler", null);
  41460. }
  41461. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41462. this._uniformBuffer.setTexture("refractionSampler", null);
  41463. }
  41464. _super.prototype.unbind.call(this);
  41465. };
  41466. /**
  41467. * Binds the submesh data.
  41468. * @param world - The world matrix.
  41469. * @param mesh - The BJS mesh.
  41470. * @param subMesh - A submesh of the BJS mesh.
  41471. */
  41472. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41473. var scene = this.getScene();
  41474. var defines = subMesh._materialDefines;
  41475. if (!defines) {
  41476. return;
  41477. }
  41478. var effect = subMesh.effect;
  41479. if (!effect) {
  41480. return;
  41481. }
  41482. this._activeEffect = effect;
  41483. // Matrices
  41484. this.bindOnlyWorldMatrix(world);
  41485. // Normal Matrix
  41486. if (defines.OBJECTSPACE_NORMALMAP) {
  41487. world.toNormalMatrix(this._normalMatrix);
  41488. this.bindOnlyNormalMatrix(this._normalMatrix);
  41489. }
  41490. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41491. // Bones
  41492. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41493. var reflectionTexture = null;
  41494. if (mustRebind) {
  41495. this._uniformBuffer.bindToEffect(effect, "Material");
  41496. this.bindViewProjection(effect);
  41497. reflectionTexture = this._getReflectionTexture();
  41498. var refractionTexture = this._getRefractionTexture();
  41499. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41500. // Texture uniforms
  41501. if (scene.texturesEnabled) {
  41502. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41503. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41504. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41505. }
  41506. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41507. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41508. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41509. }
  41510. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41511. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41512. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41513. }
  41514. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41515. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41516. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41517. if (reflectionTexture.boundingBoxSize) {
  41518. var cubeTexture = reflectionTexture;
  41519. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41520. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41521. }
  41522. var polynomials = reflectionTexture.sphericalPolynomial;
  41523. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41524. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41525. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41526. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41527. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41528. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41529. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41530. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41531. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41532. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41533. }
  41534. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41535. }
  41536. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41537. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41538. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41539. }
  41540. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41541. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41542. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41543. }
  41544. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41545. if (this._metallicTexture) {
  41546. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41547. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41548. }
  41549. else if (this._reflectivityTexture) {
  41550. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41551. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41552. }
  41553. if (this._microSurfaceTexture) {
  41554. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41555. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41556. }
  41557. }
  41558. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41559. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41560. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41561. if (scene._mirroredCameraPosition) {
  41562. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41563. }
  41564. else {
  41565. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41566. }
  41567. }
  41568. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41569. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41570. var depth = 1.0;
  41571. if (!refractionTexture.isCube) {
  41572. if (refractionTexture.depth) {
  41573. depth = refractionTexture.depth;
  41574. }
  41575. }
  41576. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41577. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41578. }
  41579. }
  41580. // Point size
  41581. if (this.pointsCloud) {
  41582. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41583. }
  41584. // Colors
  41585. if (defines.METALLICWORKFLOW) {
  41586. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41587. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41588. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41589. }
  41590. else {
  41591. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41592. }
  41593. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41594. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41595. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41596. // Misc
  41597. this._lightingInfos.x = this._directIntensity;
  41598. this._lightingInfos.y = this._emissiveIntensity;
  41599. this._lightingInfos.z = this._environmentIntensity;
  41600. this._lightingInfos.w = this._specularIntensity;
  41601. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41602. }
  41603. // Textures
  41604. if (scene.texturesEnabled) {
  41605. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41606. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41607. }
  41608. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41609. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41610. }
  41611. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41612. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41613. }
  41614. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41615. if (defines.LODBASEDMICROSFURACE) {
  41616. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41617. }
  41618. else {
  41619. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41620. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41621. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41622. }
  41623. }
  41624. if (defines.ENVIRONMENTBRDF) {
  41625. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41626. }
  41627. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41628. if (defines.LODBASEDMICROSFURACE) {
  41629. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41630. }
  41631. else {
  41632. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41633. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41634. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41635. }
  41636. }
  41637. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41638. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41639. }
  41640. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41641. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41642. }
  41643. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41644. if (this._metallicTexture) {
  41645. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41646. }
  41647. else if (this._reflectivityTexture) {
  41648. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41649. }
  41650. if (this._microSurfaceTexture) {
  41651. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41652. }
  41653. }
  41654. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41655. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41656. }
  41657. }
  41658. // Clip plane
  41659. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41660. // Colors
  41661. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41662. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41663. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41664. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41665. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41666. }
  41667. if (mustRebind || !this.isFrozen) {
  41668. // Lights
  41669. if (scene.lightsEnabled && !this._disableLighting) {
  41670. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41671. }
  41672. // View
  41673. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41674. this.bindView(effect);
  41675. }
  41676. // Fog
  41677. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41678. // Morph targets
  41679. if (defines.NUM_MORPH_INFLUENCERS) {
  41680. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41681. }
  41682. // image processing
  41683. this._imageProcessingConfiguration.bind(this._activeEffect);
  41684. // Log. depth
  41685. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41686. }
  41687. this._uniformBuffer.update();
  41688. this._afterBind(mesh);
  41689. };
  41690. /**
  41691. * Returns the animatable textures.
  41692. * @returns - Array of animatable textures.
  41693. */
  41694. PBRBaseMaterial.prototype.getAnimatables = function () {
  41695. var results = [];
  41696. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41697. results.push(this._albedoTexture);
  41698. }
  41699. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41700. results.push(this._ambientTexture);
  41701. }
  41702. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41703. results.push(this._opacityTexture);
  41704. }
  41705. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41706. results.push(this._reflectionTexture);
  41707. }
  41708. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41709. results.push(this._emissiveTexture);
  41710. }
  41711. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41712. results.push(this._metallicTexture);
  41713. }
  41714. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41715. results.push(this._reflectivityTexture);
  41716. }
  41717. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41718. results.push(this._bumpTexture);
  41719. }
  41720. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41721. results.push(this._lightmapTexture);
  41722. }
  41723. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41724. results.push(this._refractionTexture);
  41725. }
  41726. return results;
  41727. };
  41728. /**
  41729. * Returns the texture used for reflections.
  41730. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41731. */
  41732. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41733. if (this._reflectionTexture) {
  41734. return this._reflectionTexture;
  41735. }
  41736. return this.getScene().environmentTexture;
  41737. };
  41738. /**
  41739. * Returns the texture used for refraction or null if none is used.
  41740. * @returns - Refection texture if present. If no refraction texture and refraction
  41741. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41742. */
  41743. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41744. if (this._refractionTexture) {
  41745. return this._refractionTexture;
  41746. }
  41747. if (this._linkRefractionWithTransparency) {
  41748. return this.getScene().environmentTexture;
  41749. }
  41750. return null;
  41751. };
  41752. /**
  41753. * Disposes the resources of the material.
  41754. * @param forceDisposeEffect - Forces the disposal of effects.
  41755. * @param forceDisposeTextures - Forces the disposal of all textures.
  41756. */
  41757. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41758. if (forceDisposeTextures) {
  41759. if (this._albedoTexture) {
  41760. this._albedoTexture.dispose();
  41761. }
  41762. if (this._ambientTexture) {
  41763. this._ambientTexture.dispose();
  41764. }
  41765. if (this._opacityTexture) {
  41766. this._opacityTexture.dispose();
  41767. }
  41768. if (this._reflectionTexture) {
  41769. this._reflectionTexture.dispose();
  41770. }
  41771. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41772. this._environmentBRDFTexture.dispose();
  41773. }
  41774. if (this._emissiveTexture) {
  41775. this._emissiveTexture.dispose();
  41776. }
  41777. if (this._metallicTexture) {
  41778. this._metallicTexture.dispose();
  41779. }
  41780. if (this._reflectivityTexture) {
  41781. this._reflectivityTexture.dispose();
  41782. }
  41783. if (this._bumpTexture) {
  41784. this._bumpTexture.dispose();
  41785. }
  41786. if (this._lightmapTexture) {
  41787. this._lightmapTexture.dispose();
  41788. }
  41789. if (this._refractionTexture) {
  41790. this._refractionTexture.dispose();
  41791. }
  41792. }
  41793. this._renderTargets.dispose();
  41794. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41795. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41796. }
  41797. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41798. };
  41799. /**
  41800. * Stores the reflectivity values based on metallic roughness workflow.
  41801. */
  41802. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41803. __decorate([
  41804. BABYLON.serializeAsImageProcessingConfiguration()
  41805. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41806. __decorate([
  41807. BABYLON.serialize()
  41808. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41809. __decorate([
  41810. BABYLON.serialize()
  41811. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41812. return PBRBaseMaterial;
  41813. }(BABYLON.PushMaterial));
  41814. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41815. })(BABYLON || (BABYLON = {}));
  41816. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41817. var BABYLON;
  41818. (function (BABYLON) {
  41819. /**
  41820. * The Physically based simple base material of BJS.
  41821. *
  41822. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41823. * It is used as the base class for both the specGloss and metalRough conventions.
  41824. */
  41825. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41826. __extends(PBRBaseSimpleMaterial, _super);
  41827. /**
  41828. * Instantiates a new PBRMaterial instance.
  41829. *
  41830. * @param name The material name
  41831. * @param scene The scene the material will be use in.
  41832. */
  41833. function PBRBaseSimpleMaterial(name, scene) {
  41834. var _this = _super.call(this, name, scene) || this;
  41835. /**
  41836. * Number of Simultaneous lights allowed on the material.
  41837. */
  41838. _this.maxSimultaneousLights = 4;
  41839. /**
  41840. * If sets to true, disables all the lights affecting the material.
  41841. */
  41842. _this.disableLighting = false;
  41843. /**
  41844. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41845. */
  41846. _this.invertNormalMapX = false;
  41847. /**
  41848. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41849. */
  41850. _this.invertNormalMapY = false;
  41851. /**
  41852. * Emissivie color used to self-illuminate the model.
  41853. */
  41854. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41855. /**
  41856. * Occlusion Channel Strenght.
  41857. */
  41858. _this.occlusionStrength = 1.0;
  41859. _this.useLightmapAsShadowmap = false;
  41860. _this._useAlphaFromAlbedoTexture = true;
  41861. _this._useAmbientInGrayScale = true;
  41862. return _this;
  41863. }
  41864. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41865. /**
  41866. * Gets the current double sided mode.
  41867. */
  41868. get: function () {
  41869. return this._twoSidedLighting;
  41870. },
  41871. /**
  41872. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41873. */
  41874. set: function (value) {
  41875. if (this._twoSidedLighting === value) {
  41876. return;
  41877. }
  41878. this._twoSidedLighting = value;
  41879. this.backFaceCulling = !value;
  41880. this._markAllSubMeshesAsTexturesDirty();
  41881. },
  41882. enumerable: true,
  41883. configurable: true
  41884. });
  41885. /**
  41886. * Return the active textures of the material.
  41887. */
  41888. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41889. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41890. if (this.environmentTexture) {
  41891. activeTextures.push(this.environmentTexture);
  41892. }
  41893. if (this.normalTexture) {
  41894. activeTextures.push(this.normalTexture);
  41895. }
  41896. if (this.emissiveTexture) {
  41897. activeTextures.push(this.emissiveTexture);
  41898. }
  41899. if (this.occlusionTexture) {
  41900. activeTextures.push(this.occlusionTexture);
  41901. }
  41902. if (this.lightmapTexture) {
  41903. activeTextures.push(this.lightmapTexture);
  41904. }
  41905. return activeTextures;
  41906. };
  41907. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41908. if (_super.prototype.hasTexture.call(this, texture)) {
  41909. return true;
  41910. }
  41911. if (this.lightmapTexture === texture) {
  41912. return true;
  41913. }
  41914. return false;
  41915. };
  41916. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41917. return "PBRBaseSimpleMaterial";
  41918. };
  41919. __decorate([
  41920. BABYLON.serialize(),
  41921. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41922. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41923. __decorate([
  41924. BABYLON.serialize(),
  41925. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41926. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41927. __decorate([
  41928. BABYLON.serializeAsTexture(),
  41929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41930. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41931. __decorate([
  41932. BABYLON.serialize(),
  41933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41934. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41935. __decorate([
  41936. BABYLON.serialize(),
  41937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41938. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41939. __decorate([
  41940. BABYLON.serializeAsTexture(),
  41941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41942. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41943. __decorate([
  41944. BABYLON.serializeAsColor3("emissive"),
  41945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41946. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41947. __decorate([
  41948. BABYLON.serializeAsTexture(),
  41949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41950. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41951. __decorate([
  41952. BABYLON.serialize(),
  41953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41954. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41955. __decorate([
  41956. BABYLON.serializeAsTexture(),
  41957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41958. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41959. __decorate([
  41960. BABYLON.serialize(),
  41961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41962. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41963. __decorate([
  41964. BABYLON.serialize()
  41965. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41966. __decorate([
  41967. BABYLON.serializeAsTexture(),
  41968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41969. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41970. __decorate([
  41971. BABYLON.serialize(),
  41972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41973. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41974. return PBRBaseSimpleMaterial;
  41975. }(BABYLON.PBRBaseMaterial));
  41976. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41977. })(BABYLON || (BABYLON = {}));
  41978. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41979. var BABYLON;
  41980. (function (BABYLON) {
  41981. /**
  41982. * The Physically based material of BJS.
  41983. *
  41984. * This offers the main features of a standard PBR material.
  41985. * For more information, please refer to the documentation :
  41986. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41987. */
  41988. var PBRMaterial = /** @class */ (function (_super) {
  41989. __extends(PBRMaterial, _super);
  41990. /**
  41991. * Instantiates a new PBRMaterial instance.
  41992. *
  41993. * @param name The material name
  41994. * @param scene The scene the material will be use in.
  41995. */
  41996. function PBRMaterial(name, scene) {
  41997. var _this = _super.call(this, name, scene) || this;
  41998. /**
  41999. * Intensity of the direct lights e.g. the four lights available in your scene.
  42000. * This impacts both the direct diffuse and specular highlights.
  42001. */
  42002. _this.directIntensity = 1.0;
  42003. /**
  42004. * Intensity of the emissive part of the material.
  42005. * This helps controlling the emissive effect without modifying the emissive color.
  42006. */
  42007. _this.emissiveIntensity = 1.0;
  42008. /**
  42009. * Intensity of the environment e.g. how much the environment will light the object
  42010. * either through harmonics for rough material or through the refelction for shiny ones.
  42011. */
  42012. _this.environmentIntensity = 1.0;
  42013. /**
  42014. * This is a special control allowing the reduction of the specular highlights coming from the
  42015. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42016. */
  42017. _this.specularIntensity = 1.0;
  42018. /**
  42019. * Debug Control allowing disabling the bump map on this material.
  42020. */
  42021. _this.disableBumpMap = false;
  42022. /**
  42023. * AKA Occlusion Texture Intensity in other nomenclature.
  42024. */
  42025. _this.ambientTextureStrength = 1.0;
  42026. /**
  42027. * The color of a material in ambient lighting.
  42028. */
  42029. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42030. /**
  42031. * AKA Diffuse Color in other nomenclature.
  42032. */
  42033. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42034. /**
  42035. * AKA Specular Color in other nomenclature.
  42036. */
  42037. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42038. /**
  42039. * The color reflected from the material.
  42040. */
  42041. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42042. /**
  42043. * The color emitted from the material.
  42044. */
  42045. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42046. /**
  42047. * AKA Glossiness in other nomenclature.
  42048. */
  42049. _this.microSurface = 1.0;
  42050. /**
  42051. * source material index of refraction (IOR)' / 'destination material IOR.
  42052. */
  42053. _this.indexOfRefraction = 0.66;
  42054. /**
  42055. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42056. */
  42057. _this.invertRefractionY = false;
  42058. /**
  42059. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42060. * Materials half opaque for instance using refraction could benefit from this control.
  42061. */
  42062. _this.linkRefractionWithTransparency = false;
  42063. _this.useLightmapAsShadowmap = false;
  42064. /**
  42065. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42066. */
  42067. _this.useAlphaFromAlbedoTexture = false;
  42068. /**
  42069. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42070. */
  42071. _this.forceAlphaTest = false;
  42072. /**
  42073. * Defines the alpha limits in alpha test mode.
  42074. */
  42075. _this.alphaCutOff = 0.4;
  42076. /**
  42077. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42078. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42079. */
  42080. _this.useSpecularOverAlpha = true;
  42081. /**
  42082. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42083. */
  42084. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42085. /**
  42086. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42087. */
  42088. _this.useRoughnessFromMetallicTextureAlpha = true;
  42089. /**
  42090. * Specifies if the metallic texture contains the roughness information in its green channel.
  42091. */
  42092. _this.useRoughnessFromMetallicTextureGreen = false;
  42093. /**
  42094. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42095. */
  42096. _this.useMetallnessFromMetallicTextureBlue = false;
  42097. /**
  42098. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42099. */
  42100. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42101. /**
  42102. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42103. */
  42104. _this.useAmbientInGrayScale = false;
  42105. /**
  42106. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42107. * The material will try to infer what glossiness each pixel should be.
  42108. */
  42109. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42110. /**
  42111. * BJS is using an harcoded light falloff based on a manually sets up range.
  42112. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42113. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42114. */
  42115. _this.usePhysicalLightFalloff = true;
  42116. /**
  42117. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42118. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42119. */
  42120. _this.useRadianceOverAlpha = true;
  42121. /**
  42122. * Allows using an object space normal map (instead of tangent space).
  42123. */
  42124. _this.useObjectSpaceNormalMap = false;
  42125. /**
  42126. * Allows using the bump map in parallax mode.
  42127. */
  42128. _this.useParallax = false;
  42129. /**
  42130. * Allows using the bump map in parallax occlusion mode.
  42131. */
  42132. _this.useParallaxOcclusion = false;
  42133. /**
  42134. * Controls the scale bias of the parallax mode.
  42135. */
  42136. _this.parallaxScaleBias = 0.05;
  42137. /**
  42138. * If sets to true, disables all the lights affecting the material.
  42139. */
  42140. _this.disableLighting = false;
  42141. /**
  42142. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42143. */
  42144. _this.forceIrradianceInFragment = false;
  42145. /**
  42146. * Number of Simultaneous lights allowed on the material.
  42147. */
  42148. _this.maxSimultaneousLights = 4;
  42149. /**
  42150. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42151. */
  42152. _this.invertNormalMapX = false;
  42153. /**
  42154. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42155. */
  42156. _this.invertNormalMapY = false;
  42157. /**
  42158. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42159. */
  42160. _this.twoSidedLighting = false;
  42161. /**
  42162. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42163. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42164. */
  42165. _this.useAlphaFresnel = false;
  42166. /**
  42167. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42168. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42169. */
  42170. _this.useLinearAlphaFresnel = false;
  42171. /**
  42172. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42173. * And/Or occlude the blended part.
  42174. */
  42175. _this.environmentBRDFTexture = null;
  42176. /**
  42177. * Force normal to face away from face.
  42178. */
  42179. _this.forceNormalForward = false;
  42180. /**
  42181. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42182. * makes the reflect vector face the model (under horizon).
  42183. */
  42184. _this.useHorizonOcclusion = true;
  42185. /**
  42186. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42187. * too much the area relying on ambient texture to define their ambient occlusion.
  42188. */
  42189. _this.useRadianceOcclusion = true;
  42190. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42191. return _this;
  42192. }
  42193. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42194. /**
  42195. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42196. */
  42197. get: function () {
  42198. return this._PBRMATERIAL_OPAQUE;
  42199. },
  42200. enumerable: true,
  42201. configurable: true
  42202. });
  42203. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42204. /**
  42205. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42206. */
  42207. get: function () {
  42208. return this._PBRMATERIAL_ALPHATEST;
  42209. },
  42210. enumerable: true,
  42211. configurable: true
  42212. });
  42213. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42214. /**
  42215. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42216. */
  42217. get: function () {
  42218. return this._PBRMATERIAL_ALPHABLEND;
  42219. },
  42220. enumerable: true,
  42221. configurable: true
  42222. });
  42223. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42224. /**
  42225. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42226. * They are also discarded below the alpha cutoff threshold to improve performances.
  42227. */
  42228. get: function () {
  42229. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42230. },
  42231. enumerable: true,
  42232. configurable: true
  42233. });
  42234. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42235. /**
  42236. * Gets the image processing configuration used either in this material.
  42237. */
  42238. get: function () {
  42239. return this._imageProcessingConfiguration;
  42240. },
  42241. /**
  42242. * Sets the Default image processing configuration used either in the this material.
  42243. *
  42244. * If sets to null, the scene one is in use.
  42245. */
  42246. set: function (value) {
  42247. this._attachImageProcessingConfiguration(value);
  42248. // Ensure the effect will be rebuilt.
  42249. this._markAllSubMeshesAsTexturesDirty();
  42250. },
  42251. enumerable: true,
  42252. configurable: true
  42253. });
  42254. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42255. /**
  42256. * Gets wether the color curves effect is enabled.
  42257. */
  42258. get: function () {
  42259. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42260. },
  42261. /**
  42262. * Sets wether the color curves effect is enabled.
  42263. */
  42264. set: function (value) {
  42265. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42266. },
  42267. enumerable: true,
  42268. configurable: true
  42269. });
  42270. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42271. /**
  42272. * Gets wether the color grading effect is enabled.
  42273. */
  42274. get: function () {
  42275. return this.imageProcessingConfiguration.colorGradingEnabled;
  42276. },
  42277. /**
  42278. * Gets wether the color grading effect is enabled.
  42279. */
  42280. set: function (value) {
  42281. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42282. },
  42283. enumerable: true,
  42284. configurable: true
  42285. });
  42286. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42287. /**
  42288. * Gets wether tonemapping is enabled or not.
  42289. */
  42290. get: function () {
  42291. return this._imageProcessingConfiguration.toneMappingEnabled;
  42292. },
  42293. /**
  42294. * Sets wether tonemapping is enabled or not
  42295. */
  42296. set: function (value) {
  42297. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42298. },
  42299. enumerable: true,
  42300. configurable: true
  42301. });
  42302. ;
  42303. ;
  42304. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42305. /**
  42306. * The camera exposure used on this material.
  42307. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42308. * This corresponds to a photographic exposure.
  42309. */
  42310. get: function () {
  42311. return this._imageProcessingConfiguration.exposure;
  42312. },
  42313. /**
  42314. * The camera exposure used on this material.
  42315. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42316. * This corresponds to a photographic exposure.
  42317. */
  42318. set: function (value) {
  42319. this._imageProcessingConfiguration.exposure = value;
  42320. },
  42321. enumerable: true,
  42322. configurable: true
  42323. });
  42324. ;
  42325. ;
  42326. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42327. /**
  42328. * Gets The camera contrast used on this material.
  42329. */
  42330. get: function () {
  42331. return this._imageProcessingConfiguration.contrast;
  42332. },
  42333. /**
  42334. * Sets The camera contrast used on this material.
  42335. */
  42336. set: function (value) {
  42337. this._imageProcessingConfiguration.contrast = value;
  42338. },
  42339. enumerable: true,
  42340. configurable: true
  42341. });
  42342. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42343. /**
  42344. * Gets the Color Grading 2D Lookup Texture.
  42345. */
  42346. get: function () {
  42347. return this._imageProcessingConfiguration.colorGradingTexture;
  42348. },
  42349. /**
  42350. * Sets the Color Grading 2D Lookup Texture.
  42351. */
  42352. set: function (value) {
  42353. this._imageProcessingConfiguration.colorGradingTexture = value;
  42354. },
  42355. enumerable: true,
  42356. configurable: true
  42357. });
  42358. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42359. /**
  42360. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42361. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42362. * 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;
  42363. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42364. */
  42365. get: function () {
  42366. return this._imageProcessingConfiguration.colorCurves;
  42367. },
  42368. /**
  42369. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42370. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42371. * 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;
  42372. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42373. */
  42374. set: function (value) {
  42375. this._imageProcessingConfiguration.colorCurves = value;
  42376. },
  42377. enumerable: true,
  42378. configurable: true
  42379. });
  42380. /**
  42381. * Returns the name of this material class.
  42382. */
  42383. PBRMaterial.prototype.getClassName = function () {
  42384. return "PBRMaterial";
  42385. };
  42386. /**
  42387. * Returns an array of the actively used textures.
  42388. * @returns - Array of BaseTextures
  42389. */
  42390. PBRMaterial.prototype.getActiveTextures = function () {
  42391. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42392. if (this._albedoTexture) {
  42393. activeTextures.push(this._albedoTexture);
  42394. }
  42395. if (this._ambientTexture) {
  42396. activeTextures.push(this._ambientTexture);
  42397. }
  42398. if (this._opacityTexture) {
  42399. activeTextures.push(this._opacityTexture);
  42400. }
  42401. if (this._reflectionTexture) {
  42402. activeTextures.push(this._reflectionTexture);
  42403. }
  42404. if (this._emissiveTexture) {
  42405. activeTextures.push(this._emissiveTexture);
  42406. }
  42407. if (this._reflectivityTexture) {
  42408. activeTextures.push(this._reflectivityTexture);
  42409. }
  42410. if (this._metallicTexture) {
  42411. activeTextures.push(this._metallicTexture);
  42412. }
  42413. if (this._microSurfaceTexture) {
  42414. activeTextures.push(this._microSurfaceTexture);
  42415. }
  42416. if (this._bumpTexture) {
  42417. activeTextures.push(this._bumpTexture);
  42418. }
  42419. if (this._lightmapTexture) {
  42420. activeTextures.push(this._lightmapTexture);
  42421. }
  42422. if (this._refractionTexture) {
  42423. activeTextures.push(this._refractionTexture);
  42424. }
  42425. return activeTextures;
  42426. };
  42427. /**
  42428. * Checks to see if a texture is used in the material.
  42429. * @param texture - Base texture to use.
  42430. * @returns - Boolean specifying if a texture is used in the material.
  42431. */
  42432. PBRMaterial.prototype.hasTexture = function (texture) {
  42433. if (_super.prototype.hasTexture.call(this, texture)) {
  42434. return true;
  42435. }
  42436. if (this._albedoTexture === texture) {
  42437. return true;
  42438. }
  42439. if (this._ambientTexture === texture) {
  42440. return true;
  42441. }
  42442. if (this._opacityTexture === texture) {
  42443. return true;
  42444. }
  42445. if (this._reflectionTexture === texture) {
  42446. return true;
  42447. }
  42448. if (this._reflectivityTexture === texture) {
  42449. return true;
  42450. }
  42451. if (this._metallicTexture === texture) {
  42452. return true;
  42453. }
  42454. if (this._microSurfaceTexture === texture) {
  42455. return true;
  42456. }
  42457. if (this._bumpTexture === texture) {
  42458. return true;
  42459. }
  42460. if (this._lightmapTexture === texture) {
  42461. return true;
  42462. }
  42463. if (this._refractionTexture === texture) {
  42464. return true;
  42465. }
  42466. return false;
  42467. };
  42468. /**
  42469. * Makes a duplicate of the current material.
  42470. * @param name - name to use for the new material.
  42471. */
  42472. PBRMaterial.prototype.clone = function (name) {
  42473. var _this = this;
  42474. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42475. clone.id = name;
  42476. clone.name = name;
  42477. return clone;
  42478. };
  42479. /**
  42480. * Serializes this PBR Material.
  42481. * @returns - An object with the serialized material.
  42482. */
  42483. PBRMaterial.prototype.serialize = function () {
  42484. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42485. serializationObject.customType = "BABYLON.PBRMaterial";
  42486. return serializationObject;
  42487. };
  42488. // Statics
  42489. /**
  42490. * Parses a PBR Material from a serialized object.
  42491. * @param source - Serialized object.
  42492. * @param scene - BJS scene instance.
  42493. * @param rootUrl - url for the scene object
  42494. * @returns - PBRMaterial
  42495. */
  42496. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42497. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42498. };
  42499. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42500. /**
  42501. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42502. */
  42503. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42504. /**
  42505. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42506. */
  42507. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42508. /**
  42509. * 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.
  42510. * They are also discarded below the alpha cutoff threshold to improve performances.
  42511. */
  42512. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42513. __decorate([
  42514. BABYLON.serialize(),
  42515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42516. ], PBRMaterial.prototype, "directIntensity", void 0);
  42517. __decorate([
  42518. BABYLON.serialize(),
  42519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42520. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42521. __decorate([
  42522. BABYLON.serialize(),
  42523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42524. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42525. __decorate([
  42526. BABYLON.serialize(),
  42527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42528. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42529. __decorate([
  42530. BABYLON.serialize(),
  42531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42532. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42533. __decorate([
  42534. BABYLON.serializeAsTexture(),
  42535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42536. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42537. __decorate([
  42538. BABYLON.serializeAsTexture(),
  42539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42540. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42541. __decorate([
  42542. BABYLON.serialize(),
  42543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42544. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42545. __decorate([
  42546. BABYLON.serializeAsTexture(),
  42547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42548. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42549. __decorate([
  42550. BABYLON.serializeAsTexture(),
  42551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42552. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42553. __decorate([
  42554. BABYLON.serializeAsTexture(),
  42555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42556. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42557. __decorate([
  42558. BABYLON.serializeAsTexture(),
  42559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42560. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42561. __decorate([
  42562. BABYLON.serializeAsTexture(),
  42563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42564. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42565. __decorate([
  42566. BABYLON.serialize(),
  42567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42568. ], PBRMaterial.prototype, "metallic", void 0);
  42569. __decorate([
  42570. BABYLON.serialize(),
  42571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42572. ], PBRMaterial.prototype, "roughness", void 0);
  42573. __decorate([
  42574. BABYLON.serializeAsTexture(),
  42575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42576. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42577. __decorate([
  42578. BABYLON.serializeAsTexture(),
  42579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42580. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42581. __decorate([
  42582. BABYLON.serializeAsTexture(),
  42583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42584. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42585. __decorate([
  42586. BABYLON.serializeAsTexture(),
  42587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42588. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42589. __decorate([
  42590. BABYLON.serializeAsColor3("ambient"),
  42591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42592. ], PBRMaterial.prototype, "ambientColor", void 0);
  42593. __decorate([
  42594. BABYLON.serializeAsColor3("albedo"),
  42595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42596. ], PBRMaterial.prototype, "albedoColor", void 0);
  42597. __decorate([
  42598. BABYLON.serializeAsColor3("reflectivity"),
  42599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42600. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42601. __decorate([
  42602. BABYLON.serializeAsColor3("reflection"),
  42603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42604. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42605. __decorate([
  42606. BABYLON.serializeAsColor3("emissive"),
  42607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42608. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42609. __decorate([
  42610. BABYLON.serialize(),
  42611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42612. ], PBRMaterial.prototype, "microSurface", void 0);
  42613. __decorate([
  42614. BABYLON.serialize(),
  42615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42616. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42617. __decorate([
  42618. BABYLON.serialize(),
  42619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42620. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42621. __decorate([
  42622. BABYLON.serialize(),
  42623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42624. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42625. __decorate([
  42626. BABYLON.serialize(),
  42627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42628. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42629. __decorate([
  42630. BABYLON.serialize(),
  42631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42632. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42633. __decorate([
  42634. BABYLON.serialize(),
  42635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42636. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42637. __decorate([
  42638. BABYLON.serialize(),
  42639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42640. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42641. __decorate([
  42642. BABYLON.serialize(),
  42643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42644. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42645. __decorate([
  42646. BABYLON.serialize(),
  42647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42648. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42649. __decorate([
  42650. BABYLON.serialize(),
  42651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42652. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42653. __decorate([
  42654. BABYLON.serialize(),
  42655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42656. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42657. __decorate([
  42658. BABYLON.serialize(),
  42659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42660. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42661. __decorate([
  42662. BABYLON.serialize(),
  42663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42664. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42665. __decorate([
  42666. BABYLON.serialize(),
  42667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42668. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42669. __decorate([
  42670. BABYLON.serialize(),
  42671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42672. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42673. __decorate([
  42674. BABYLON.serialize(),
  42675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42676. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42677. __decorate([
  42678. BABYLON.serialize(),
  42679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42680. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42681. __decorate([
  42682. BABYLON.serialize(),
  42683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42684. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42685. __decorate([
  42686. BABYLON.serialize(),
  42687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42688. ], PBRMaterial.prototype, "useParallax", void 0);
  42689. __decorate([
  42690. BABYLON.serialize(),
  42691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42692. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42693. __decorate([
  42694. BABYLON.serialize(),
  42695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42696. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42697. __decorate([
  42698. BABYLON.serialize(),
  42699. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42700. ], PBRMaterial.prototype, "disableLighting", void 0);
  42701. __decorate([
  42702. BABYLON.serialize(),
  42703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42704. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42705. __decorate([
  42706. BABYLON.serialize(),
  42707. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42708. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42709. __decorate([
  42710. BABYLON.serialize(),
  42711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42712. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42713. __decorate([
  42714. BABYLON.serialize(),
  42715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42716. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42717. __decorate([
  42718. BABYLON.serialize(),
  42719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42720. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42721. __decorate([
  42722. BABYLON.serialize(),
  42723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42724. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42725. __decorate([
  42726. BABYLON.serialize(),
  42727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42728. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42729. __decorate([
  42730. BABYLON.serializeAsTexture(),
  42731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42732. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42733. __decorate([
  42734. BABYLON.serialize(),
  42735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42736. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42737. __decorate([
  42738. BABYLON.serialize(),
  42739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42740. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42741. __decorate([
  42742. BABYLON.serialize(),
  42743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42744. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42745. return PBRMaterial;
  42746. }(BABYLON.PBRBaseMaterial));
  42747. BABYLON.PBRMaterial = PBRMaterial;
  42748. })(BABYLON || (BABYLON = {}));
  42749. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42750. var BABYLON;
  42751. (function (BABYLON) {
  42752. /**
  42753. * The PBR material of BJS following the metal roughness convention.
  42754. *
  42755. * This fits to the PBR convention in the GLTF definition:
  42756. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42757. */
  42758. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42759. __extends(PBRMetallicRoughnessMaterial, _super);
  42760. /**
  42761. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42762. *
  42763. * @param name The material name
  42764. * @param scene The scene the material will be use in.
  42765. */
  42766. function PBRMetallicRoughnessMaterial(name, scene) {
  42767. var _this = _super.call(this, name, scene) || this;
  42768. _this._useRoughnessFromMetallicTextureAlpha = false;
  42769. _this._useRoughnessFromMetallicTextureGreen = true;
  42770. _this._useMetallnessFromMetallicTextureBlue = true;
  42771. _this.metallic = 1.0;
  42772. _this.roughness = 1.0;
  42773. return _this;
  42774. }
  42775. /**
  42776. * Return the currrent class name of the material.
  42777. */
  42778. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42779. return "PBRMetallicRoughnessMaterial";
  42780. };
  42781. /**
  42782. * Return the active textures of the material.
  42783. */
  42784. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42785. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42786. if (this.baseTexture) {
  42787. activeTextures.push(this.baseTexture);
  42788. }
  42789. if (this.metallicRoughnessTexture) {
  42790. activeTextures.push(this.metallicRoughnessTexture);
  42791. }
  42792. return activeTextures;
  42793. };
  42794. /**
  42795. * Checks to see if a texture is used in the material.
  42796. * @param texture - Base texture to use.
  42797. * @returns - Boolean specifying if a texture is used in the material.
  42798. */
  42799. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42800. if (_super.prototype.hasTexture.call(this, texture)) {
  42801. return true;
  42802. }
  42803. if (this.baseTexture === texture) {
  42804. return true;
  42805. }
  42806. if (this.metallicRoughnessTexture === texture) {
  42807. return true;
  42808. }
  42809. return false;
  42810. };
  42811. /**
  42812. * Makes a duplicate of the current material.
  42813. * @param name - name to use for the new material.
  42814. */
  42815. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42816. var _this = this;
  42817. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42818. clone.id = name;
  42819. clone.name = name;
  42820. return clone;
  42821. };
  42822. /**
  42823. * Serialize the material to a parsable JSON object.
  42824. */
  42825. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42826. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42827. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42828. return serializationObject;
  42829. };
  42830. /**
  42831. * Parses a JSON object correponding to the serialize function.
  42832. */
  42833. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42834. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42835. };
  42836. __decorate([
  42837. BABYLON.serializeAsColor3(),
  42838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42839. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42840. __decorate([
  42841. BABYLON.serializeAsTexture(),
  42842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42843. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42844. __decorate([
  42845. BABYLON.serialize(),
  42846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42847. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42848. __decorate([
  42849. BABYLON.serialize(),
  42850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42851. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42852. __decorate([
  42853. BABYLON.serializeAsTexture(),
  42854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42855. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42856. return PBRMetallicRoughnessMaterial;
  42857. }(BABYLON.PBRBaseSimpleMaterial));
  42858. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42859. })(BABYLON || (BABYLON = {}));
  42860. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42861. var BABYLON;
  42862. (function (BABYLON) {
  42863. /**
  42864. * The PBR material of BJS following the specular glossiness convention.
  42865. *
  42866. * This fits to the PBR convention in the GLTF definition:
  42867. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42868. */
  42869. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42870. __extends(PBRSpecularGlossinessMaterial, _super);
  42871. /**
  42872. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42873. *
  42874. * @param name The material name
  42875. * @param scene The scene the material will be use in.
  42876. */
  42877. function PBRSpecularGlossinessMaterial(name, scene) {
  42878. var _this = _super.call(this, name, scene) || this;
  42879. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42880. return _this;
  42881. }
  42882. /**
  42883. * Return the currrent class name of the material.
  42884. */
  42885. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42886. return "PBRSpecularGlossinessMaterial";
  42887. };
  42888. /**
  42889. * Return the active textures of the material.
  42890. */
  42891. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42892. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42893. if (this.diffuseTexture) {
  42894. activeTextures.push(this.diffuseTexture);
  42895. }
  42896. if (this.specularGlossinessTexture) {
  42897. activeTextures.push(this.specularGlossinessTexture);
  42898. }
  42899. return activeTextures;
  42900. };
  42901. /**
  42902. * Checks to see if a texture is used in the material.
  42903. * @param texture - Base texture to use.
  42904. * @returns - Boolean specifying if a texture is used in the material.
  42905. */
  42906. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42907. if (_super.prototype.hasTexture.call(this, texture)) {
  42908. return true;
  42909. }
  42910. if (this.diffuseTexture === texture) {
  42911. return true;
  42912. }
  42913. if (this.specularGlossinessTexture === texture) {
  42914. return true;
  42915. }
  42916. return false;
  42917. };
  42918. /**
  42919. * Makes a duplicate of the current material.
  42920. * @param name - name to use for the new material.
  42921. */
  42922. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42923. var _this = this;
  42924. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42925. clone.id = name;
  42926. clone.name = name;
  42927. return clone;
  42928. };
  42929. /**
  42930. * Serialize the material to a parsable JSON object.
  42931. */
  42932. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42933. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42934. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42935. return serializationObject;
  42936. };
  42937. /**
  42938. * Parses a JSON object correponding to the serialize function.
  42939. */
  42940. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42941. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42942. };
  42943. __decorate([
  42944. BABYLON.serializeAsColor3("diffuse"),
  42945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42946. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42947. __decorate([
  42948. BABYLON.serializeAsTexture(),
  42949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42950. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42951. __decorate([
  42952. BABYLON.serializeAsColor3("specular"),
  42953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42954. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42955. __decorate([
  42956. BABYLON.serialize(),
  42957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42958. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42959. __decorate([
  42960. BABYLON.serializeAsTexture(),
  42961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42962. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42963. return PBRSpecularGlossinessMaterial;
  42964. }(BABYLON.PBRBaseSimpleMaterial));
  42965. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42966. })(BABYLON || (BABYLON = {}));
  42967. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42968. var BABYLON;
  42969. (function (BABYLON) {
  42970. BABYLON.CameraInputTypes = {};
  42971. var CameraInputsManager = /** @class */ (function () {
  42972. function CameraInputsManager(camera) {
  42973. this.attached = {};
  42974. this.camera = camera;
  42975. this.checkInputs = function () { };
  42976. }
  42977. /**
  42978. * Add an input method to a camera.
  42979. * builtin inputs example: camera.inputs.addGamepad();
  42980. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42981. * @param input camera input method
  42982. */
  42983. CameraInputsManager.prototype.add = function (input) {
  42984. var type = input.getSimpleName();
  42985. if (this.attached[type]) {
  42986. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42987. return;
  42988. }
  42989. this.attached[type] = input;
  42990. input.camera = this.camera;
  42991. //for checkInputs, we are dynamically creating a function
  42992. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42993. if (input.checkInputs) {
  42994. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42995. }
  42996. if (this.attachedElement) {
  42997. input.attachControl(this.attachedElement);
  42998. }
  42999. };
  43000. /**
  43001. * Remove a specific input method from a camera
  43002. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43003. * @param inputToRemove camera input method
  43004. */
  43005. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43006. for (var cam in this.attached) {
  43007. var input = this.attached[cam];
  43008. if (input === inputToRemove) {
  43009. input.detachControl(this.attachedElement);
  43010. input.camera = null;
  43011. delete this.attached[cam];
  43012. this.rebuildInputCheck();
  43013. }
  43014. }
  43015. };
  43016. CameraInputsManager.prototype.removeByType = function (inputType) {
  43017. for (var cam in this.attached) {
  43018. var input = this.attached[cam];
  43019. if (input.getClassName() === inputType) {
  43020. input.detachControl(this.attachedElement);
  43021. input.camera = null;
  43022. delete this.attached[cam];
  43023. this.rebuildInputCheck();
  43024. }
  43025. }
  43026. };
  43027. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43028. var current = this.checkInputs;
  43029. return function () {
  43030. current();
  43031. fn();
  43032. };
  43033. };
  43034. CameraInputsManager.prototype.attachInput = function (input) {
  43035. if (this.attachedElement) {
  43036. input.attachControl(this.attachedElement, this.noPreventDefault);
  43037. }
  43038. };
  43039. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43040. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43041. if (this.attachedElement) {
  43042. return;
  43043. }
  43044. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43045. this.attachedElement = element;
  43046. this.noPreventDefault = noPreventDefault;
  43047. for (var cam in this.attached) {
  43048. this.attached[cam].attachControl(element, noPreventDefault);
  43049. }
  43050. };
  43051. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43052. if (disconnect === void 0) { disconnect = false; }
  43053. if (this.attachedElement !== element) {
  43054. return;
  43055. }
  43056. for (var cam in this.attached) {
  43057. this.attached[cam].detachControl(element);
  43058. if (disconnect) {
  43059. this.attached[cam].camera = null;
  43060. }
  43061. }
  43062. this.attachedElement = null;
  43063. };
  43064. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43065. this.checkInputs = function () { };
  43066. for (var cam in this.attached) {
  43067. var input = this.attached[cam];
  43068. if (input.checkInputs) {
  43069. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43070. }
  43071. }
  43072. };
  43073. /**
  43074. * Remove all attached input methods from a camera
  43075. */
  43076. CameraInputsManager.prototype.clear = function () {
  43077. if (this.attachedElement) {
  43078. this.detachElement(this.attachedElement, true);
  43079. }
  43080. this.attached = {};
  43081. this.attachedElement = null;
  43082. this.checkInputs = function () { };
  43083. };
  43084. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43085. var inputs = {};
  43086. for (var cam in this.attached) {
  43087. var input = this.attached[cam];
  43088. var res = BABYLON.SerializationHelper.Serialize(input);
  43089. inputs[input.getClassName()] = res;
  43090. }
  43091. serializedCamera.inputsmgr = inputs;
  43092. };
  43093. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43094. var parsedInputs = parsedCamera.inputsmgr;
  43095. if (parsedInputs) {
  43096. this.clear();
  43097. for (var n in parsedInputs) {
  43098. var construct = BABYLON.CameraInputTypes[n];
  43099. if (construct) {
  43100. var parsedinput = parsedInputs[n];
  43101. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43102. this.add(input);
  43103. }
  43104. }
  43105. }
  43106. else {
  43107. //2016-03-08 this part is for managing backward compatibility
  43108. for (var n in this.attached) {
  43109. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43110. if (construct) {
  43111. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43112. this.remove(this.attached[n]);
  43113. this.add(input);
  43114. }
  43115. }
  43116. }
  43117. };
  43118. return CameraInputsManager;
  43119. }());
  43120. BABYLON.CameraInputsManager = CameraInputsManager;
  43121. })(BABYLON || (BABYLON = {}));
  43122. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43123. var BABYLON;
  43124. (function (BABYLON) {
  43125. var TargetCamera = /** @class */ (function (_super) {
  43126. __extends(TargetCamera, _super);
  43127. function TargetCamera(name, position, scene) {
  43128. var _this = _super.call(this, name, position, scene) || this;
  43129. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43130. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43131. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43132. _this.speed = 2.0;
  43133. _this.noRotationConstraint = false;
  43134. _this.lockedTarget = null;
  43135. _this._currentTarget = BABYLON.Vector3.Zero();
  43136. _this._viewMatrix = BABYLON.Matrix.Zero();
  43137. _this._camMatrix = BABYLON.Matrix.Zero();
  43138. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43139. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43140. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43141. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43142. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43143. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43144. _this._tempMatrix = BABYLON.Matrix.Zero();
  43145. return _this;
  43146. }
  43147. TargetCamera.prototype.getFrontPosition = function (distance) {
  43148. this.getWorldMatrix();
  43149. var direction = this.getTarget().subtract(this.position);
  43150. direction.normalize();
  43151. direction.scaleInPlace(distance);
  43152. return this.globalPosition.add(direction);
  43153. };
  43154. TargetCamera.prototype._getLockedTargetPosition = function () {
  43155. if (!this.lockedTarget) {
  43156. return null;
  43157. }
  43158. if (this.lockedTarget.absolutePosition) {
  43159. this.lockedTarget.computeWorldMatrix();
  43160. }
  43161. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43162. };
  43163. TargetCamera.prototype.storeState = function () {
  43164. this._storedPosition = this.position.clone();
  43165. this._storedRotation = this.rotation.clone();
  43166. if (this.rotationQuaternion) {
  43167. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43168. }
  43169. return _super.prototype.storeState.call(this);
  43170. };
  43171. /**
  43172. * Restored camera state. You must call storeState() first
  43173. */
  43174. TargetCamera.prototype._restoreStateValues = function () {
  43175. if (!_super.prototype._restoreStateValues.call(this)) {
  43176. return false;
  43177. }
  43178. this.position = this._storedPosition.clone();
  43179. this.rotation = this._storedRotation.clone();
  43180. if (this.rotationQuaternion) {
  43181. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43182. }
  43183. this.cameraDirection.copyFromFloats(0, 0, 0);
  43184. this.cameraRotation.copyFromFloats(0, 0);
  43185. return true;
  43186. };
  43187. // Cache
  43188. TargetCamera.prototype._initCache = function () {
  43189. _super.prototype._initCache.call(this);
  43190. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43191. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43192. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43193. };
  43194. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43195. if (!ignoreParentClass) {
  43196. _super.prototype._updateCache.call(this);
  43197. }
  43198. var lockedTargetPosition = this._getLockedTargetPosition();
  43199. if (!lockedTargetPosition) {
  43200. this._cache.lockedTarget = null;
  43201. }
  43202. else {
  43203. if (!this._cache.lockedTarget) {
  43204. this._cache.lockedTarget = lockedTargetPosition.clone();
  43205. }
  43206. else {
  43207. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43208. }
  43209. }
  43210. this._cache.rotation.copyFrom(this.rotation);
  43211. if (this.rotationQuaternion)
  43212. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43213. };
  43214. // Synchronized
  43215. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43216. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43217. return false;
  43218. }
  43219. var lockedTargetPosition = this._getLockedTargetPosition();
  43220. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43221. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43222. };
  43223. // Methods
  43224. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43225. var engine = this.getEngine();
  43226. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43227. };
  43228. // Target
  43229. TargetCamera.prototype.setTarget = function (target) {
  43230. this.upVector.normalize();
  43231. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43232. this._camMatrix.invert();
  43233. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43234. var vDir = target.subtract(this.position);
  43235. if (vDir.x >= 0.0) {
  43236. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43237. }
  43238. else {
  43239. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43240. }
  43241. this.rotation.z = 0;
  43242. if (isNaN(this.rotation.x)) {
  43243. this.rotation.x = 0;
  43244. }
  43245. if (isNaN(this.rotation.y)) {
  43246. this.rotation.y = 0;
  43247. }
  43248. if (isNaN(this.rotation.z)) {
  43249. this.rotation.z = 0;
  43250. }
  43251. if (this.rotationQuaternion) {
  43252. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43253. }
  43254. };
  43255. /**
  43256. * Return the current target position of the camera. This value is expressed in local space.
  43257. */
  43258. TargetCamera.prototype.getTarget = function () {
  43259. return this._currentTarget;
  43260. };
  43261. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43262. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43263. };
  43264. TargetCamera.prototype._updatePosition = function () {
  43265. if (this.parent) {
  43266. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43267. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43268. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43269. return;
  43270. }
  43271. this.position.addInPlace(this.cameraDirection);
  43272. };
  43273. TargetCamera.prototype._checkInputs = function () {
  43274. var needToMove = this._decideIfNeedsToMove();
  43275. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43276. // Move
  43277. if (needToMove) {
  43278. this._updatePosition();
  43279. }
  43280. // Rotate
  43281. if (needToRotate) {
  43282. this.rotation.x += this.cameraRotation.x;
  43283. this.rotation.y += this.cameraRotation.y;
  43284. //rotate, if quaternion is set and rotation was used
  43285. if (this.rotationQuaternion) {
  43286. var len = this.rotation.lengthSquared();
  43287. if (len) {
  43288. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43289. }
  43290. }
  43291. if (!this.noRotationConstraint) {
  43292. var limit = (Math.PI / 2) * 0.95;
  43293. if (this.rotation.x > limit)
  43294. this.rotation.x = limit;
  43295. if (this.rotation.x < -limit)
  43296. this.rotation.x = -limit;
  43297. }
  43298. }
  43299. // Inertia
  43300. if (needToMove) {
  43301. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43302. this.cameraDirection.x = 0;
  43303. }
  43304. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43305. this.cameraDirection.y = 0;
  43306. }
  43307. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43308. this.cameraDirection.z = 0;
  43309. }
  43310. this.cameraDirection.scaleInPlace(this.inertia);
  43311. }
  43312. if (needToRotate) {
  43313. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43314. this.cameraRotation.x = 0;
  43315. }
  43316. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43317. this.cameraRotation.y = 0;
  43318. }
  43319. this.cameraRotation.scaleInPlace(this.inertia);
  43320. }
  43321. _super.prototype._checkInputs.call(this);
  43322. };
  43323. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43324. if (this.rotationQuaternion) {
  43325. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43326. }
  43327. else {
  43328. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43329. }
  43330. //update the up vector!
  43331. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43332. };
  43333. TargetCamera.prototype._getViewMatrix = function () {
  43334. if (this.lockedTarget) {
  43335. this.setTarget(this._getLockedTargetPosition());
  43336. }
  43337. // Compute
  43338. this._updateCameraRotationMatrix();
  43339. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43340. // Computing target and final matrix
  43341. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43342. if (this.getScene().useRightHandedSystem) {
  43343. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43344. }
  43345. else {
  43346. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43347. }
  43348. return this._viewMatrix;
  43349. };
  43350. /**
  43351. * @override
  43352. * Override Camera.createRigCamera
  43353. */
  43354. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43355. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43356. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43357. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43358. if (!this.rotationQuaternion) {
  43359. this.rotationQuaternion = new BABYLON.Quaternion();
  43360. }
  43361. rigCamera._cameraRigParams = {};
  43362. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43363. }
  43364. return rigCamera;
  43365. }
  43366. return null;
  43367. };
  43368. /**
  43369. * @override
  43370. * Override Camera._updateRigCameras
  43371. */
  43372. TargetCamera.prototype._updateRigCameras = function () {
  43373. var camLeft = this._rigCameras[0];
  43374. var camRight = this._rigCameras[1];
  43375. switch (this.cameraRigMode) {
  43376. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43377. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43378. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43379. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43380. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43381. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43382. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43383. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43384. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43385. camLeft.setTarget(this.getTarget());
  43386. camRight.setTarget(this.getTarget());
  43387. break;
  43388. case BABYLON.Camera.RIG_MODE_VR:
  43389. if (camLeft.rotationQuaternion) {
  43390. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43391. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43392. }
  43393. else {
  43394. camLeft.rotation.copyFrom(this.rotation);
  43395. camRight.rotation.copyFrom(this.rotation);
  43396. }
  43397. camLeft.position.copyFrom(this.position);
  43398. camRight.position.copyFrom(this.position);
  43399. break;
  43400. }
  43401. _super.prototype._updateRigCameras.call(this);
  43402. };
  43403. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43404. if (!this._rigCamTransformMatrix) {
  43405. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43406. }
  43407. var target = this.getTarget();
  43408. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43409. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43410. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43411. };
  43412. TargetCamera.prototype.getClassName = function () {
  43413. return "TargetCamera";
  43414. };
  43415. __decorate([
  43416. BABYLON.serializeAsVector3()
  43417. ], TargetCamera.prototype, "rotation", void 0);
  43418. __decorate([
  43419. BABYLON.serialize()
  43420. ], TargetCamera.prototype, "speed", void 0);
  43421. __decorate([
  43422. BABYLON.serializeAsMeshReference("lockedTargetId")
  43423. ], TargetCamera.prototype, "lockedTarget", void 0);
  43424. return TargetCamera;
  43425. }(BABYLON.Camera));
  43426. BABYLON.TargetCamera = TargetCamera;
  43427. })(BABYLON || (BABYLON = {}));
  43428. //# sourceMappingURL=babylon.targetCamera.js.map
  43429. var BABYLON;
  43430. (function (BABYLON) {
  43431. var FreeCameraMouseInput = /** @class */ (function () {
  43432. function FreeCameraMouseInput(touchEnabled) {
  43433. if (touchEnabled === void 0) { touchEnabled = true; }
  43434. this.touchEnabled = touchEnabled;
  43435. this.buttons = [0, 1, 2];
  43436. this.angularSensibility = 2000.0;
  43437. this.previousPosition = null;
  43438. }
  43439. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43440. var _this = this;
  43441. var engine = this.camera.getEngine();
  43442. if (!this._pointerInput) {
  43443. this._pointerInput = function (p, s) {
  43444. var evt = p.event;
  43445. if (engine.isInVRExclusivePointerMode) {
  43446. return;
  43447. }
  43448. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43449. return;
  43450. }
  43451. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43452. return;
  43453. }
  43454. var srcElement = (evt.srcElement || evt.target);
  43455. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43456. try {
  43457. srcElement.setPointerCapture(evt.pointerId);
  43458. }
  43459. catch (e) {
  43460. //Nothing to do with the error. Execution will continue.
  43461. }
  43462. _this.previousPosition = {
  43463. x: evt.clientX,
  43464. y: evt.clientY
  43465. };
  43466. if (!noPreventDefault) {
  43467. evt.preventDefault();
  43468. element.focus();
  43469. }
  43470. }
  43471. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43472. try {
  43473. srcElement.releasePointerCapture(evt.pointerId);
  43474. }
  43475. catch (e) {
  43476. //Nothing to do with the error.
  43477. }
  43478. _this.previousPosition = null;
  43479. if (!noPreventDefault) {
  43480. evt.preventDefault();
  43481. }
  43482. }
  43483. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43484. if (!_this.previousPosition || engine.isPointerLock) {
  43485. return;
  43486. }
  43487. var offsetX = evt.clientX - _this.previousPosition.x;
  43488. var offsetY = evt.clientY - _this.previousPosition.y;
  43489. if (_this.camera.getScene().useRightHandedSystem) {
  43490. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43491. }
  43492. else {
  43493. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43494. }
  43495. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43496. _this.previousPosition = {
  43497. x: evt.clientX,
  43498. y: evt.clientY
  43499. };
  43500. if (!noPreventDefault) {
  43501. evt.preventDefault();
  43502. }
  43503. }
  43504. };
  43505. }
  43506. this._onMouseMove = function (evt) {
  43507. if (!engine.isPointerLock) {
  43508. return;
  43509. }
  43510. if (engine.isInVRExclusivePointerMode) {
  43511. return;
  43512. }
  43513. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43514. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43515. if (_this.camera.getScene().useRightHandedSystem) {
  43516. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43517. }
  43518. else {
  43519. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43520. }
  43521. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43522. _this.previousPosition = null;
  43523. if (!noPreventDefault) {
  43524. evt.preventDefault();
  43525. }
  43526. };
  43527. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43528. element.addEventListener("mousemove", this._onMouseMove, false);
  43529. };
  43530. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43531. if (this._observer && element) {
  43532. this.camera.getScene().onPointerObservable.remove(this._observer);
  43533. if (this._onMouseMove) {
  43534. element.removeEventListener("mousemove", this._onMouseMove);
  43535. }
  43536. this._observer = null;
  43537. this._onMouseMove = null;
  43538. this.previousPosition = null;
  43539. }
  43540. };
  43541. FreeCameraMouseInput.prototype.getClassName = function () {
  43542. return "FreeCameraMouseInput";
  43543. };
  43544. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43545. return "mouse";
  43546. };
  43547. __decorate([
  43548. BABYLON.serialize()
  43549. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43550. __decorate([
  43551. BABYLON.serialize()
  43552. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43553. return FreeCameraMouseInput;
  43554. }());
  43555. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43556. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43557. })(BABYLON || (BABYLON = {}));
  43558. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43559. var BABYLON;
  43560. (function (BABYLON) {
  43561. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43562. function FreeCameraKeyboardMoveInput() {
  43563. this._keys = new Array();
  43564. this.keysUp = [38];
  43565. this.keysDown = [40];
  43566. this.keysLeft = [37];
  43567. this.keysRight = [39];
  43568. }
  43569. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43570. var _this = this;
  43571. if (this._onCanvasBlurObserver) {
  43572. return;
  43573. }
  43574. this._scene = this.camera.getScene();
  43575. this._engine = this._scene.getEngine();
  43576. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43577. _this._keys = [];
  43578. });
  43579. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43580. var evt = info.event;
  43581. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43582. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43583. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43584. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43585. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43586. var index = _this._keys.indexOf(evt.keyCode);
  43587. if (index === -1) {
  43588. _this._keys.push(evt.keyCode);
  43589. }
  43590. if (!noPreventDefault) {
  43591. evt.preventDefault();
  43592. }
  43593. }
  43594. }
  43595. else {
  43596. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43597. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43598. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43599. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43600. var index = _this._keys.indexOf(evt.keyCode);
  43601. if (index >= 0) {
  43602. _this._keys.splice(index, 1);
  43603. }
  43604. if (!noPreventDefault) {
  43605. evt.preventDefault();
  43606. }
  43607. }
  43608. }
  43609. });
  43610. };
  43611. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43612. if (this._scene) {
  43613. if (this._onKeyboardObserver) {
  43614. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43615. }
  43616. if (this._onCanvasBlurObserver) {
  43617. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43618. }
  43619. this._onKeyboardObserver = null;
  43620. this._onCanvasBlurObserver = null;
  43621. }
  43622. this._keys = [];
  43623. };
  43624. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43625. if (this._onKeyboardObserver) {
  43626. var camera = this.camera;
  43627. // Keyboard
  43628. for (var index = 0; index < this._keys.length; index++) {
  43629. var keyCode = this._keys[index];
  43630. var speed = camera._computeLocalCameraSpeed();
  43631. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43632. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43633. }
  43634. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43635. camera._localDirection.copyFromFloats(0, 0, speed);
  43636. }
  43637. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43638. camera._localDirection.copyFromFloats(speed, 0, 0);
  43639. }
  43640. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43641. camera._localDirection.copyFromFloats(0, 0, -speed);
  43642. }
  43643. if (camera.getScene().useRightHandedSystem) {
  43644. camera._localDirection.z *= -1;
  43645. }
  43646. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43647. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43648. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43649. }
  43650. }
  43651. };
  43652. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43653. return "FreeCameraKeyboardMoveInput";
  43654. };
  43655. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43656. this._keys = [];
  43657. };
  43658. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43659. return "keyboard";
  43660. };
  43661. __decorate([
  43662. BABYLON.serialize()
  43663. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43664. __decorate([
  43665. BABYLON.serialize()
  43666. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43667. __decorate([
  43668. BABYLON.serialize()
  43669. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43670. __decorate([
  43671. BABYLON.serialize()
  43672. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43673. return FreeCameraKeyboardMoveInput;
  43674. }());
  43675. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43676. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43677. })(BABYLON || (BABYLON = {}));
  43678. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43679. var BABYLON;
  43680. (function (BABYLON) {
  43681. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43682. __extends(FreeCameraInputsManager, _super);
  43683. function FreeCameraInputsManager(camera) {
  43684. return _super.call(this, camera) || this;
  43685. }
  43686. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43687. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43688. return this;
  43689. };
  43690. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43691. if (touchEnabled === void 0) { touchEnabled = true; }
  43692. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43693. return this;
  43694. };
  43695. FreeCameraInputsManager.prototype.addGamepad = function () {
  43696. this.add(new BABYLON.FreeCameraGamepadInput());
  43697. return this;
  43698. };
  43699. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43700. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43701. return this;
  43702. };
  43703. FreeCameraInputsManager.prototype.addTouch = function () {
  43704. this.add(new BABYLON.FreeCameraTouchInput());
  43705. return this;
  43706. };
  43707. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43708. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43709. return this;
  43710. };
  43711. return FreeCameraInputsManager;
  43712. }(BABYLON.CameraInputsManager));
  43713. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43714. })(BABYLON || (BABYLON = {}));
  43715. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43716. var BABYLON;
  43717. (function (BABYLON) {
  43718. var FreeCamera = /** @class */ (function (_super) {
  43719. __extends(FreeCamera, _super);
  43720. function FreeCamera(name, position, scene) {
  43721. var _this = _super.call(this, name, position, scene) || this;
  43722. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43723. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43724. _this.checkCollisions = false;
  43725. _this.applyGravity = false;
  43726. _this._needMoveForGravity = false;
  43727. _this._oldPosition = BABYLON.Vector3.Zero();
  43728. _this._diffPosition = BABYLON.Vector3.Zero();
  43729. _this._newPosition = BABYLON.Vector3.Zero();
  43730. // Collisions
  43731. _this._collisionMask = -1;
  43732. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43733. if (collidedMesh === void 0) { collidedMesh = null; }
  43734. //TODO move this to the collision coordinator!
  43735. if (_this.getScene().workerCollisions)
  43736. newPosition.multiplyInPlace(_this._collider._radius);
  43737. var updatePosition = function (newPos) {
  43738. _this._newPosition.copyFrom(newPos);
  43739. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43740. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43741. _this.position.addInPlace(_this._diffPosition);
  43742. if (_this.onCollide && collidedMesh) {
  43743. _this.onCollide(collidedMesh);
  43744. }
  43745. }
  43746. };
  43747. updatePosition(newPosition);
  43748. };
  43749. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43750. _this.inputs.addKeyboard().addMouse();
  43751. return _this;
  43752. }
  43753. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43754. //-- begin properties for backward compatibility for inputs
  43755. /**
  43756. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43757. * Higher values reduce sensitivity.
  43758. */
  43759. get: function () {
  43760. var mouse = this.inputs.attached["mouse"];
  43761. if (mouse)
  43762. return mouse.angularSensibility;
  43763. return 0;
  43764. },
  43765. /**
  43766. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43767. * Higher values reduce sensitivity.
  43768. */
  43769. set: function (value) {
  43770. var mouse = this.inputs.attached["mouse"];
  43771. if (mouse)
  43772. mouse.angularSensibility = value;
  43773. },
  43774. enumerable: true,
  43775. configurable: true
  43776. });
  43777. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43778. get: function () {
  43779. var keyboard = this.inputs.attached["keyboard"];
  43780. if (keyboard)
  43781. return keyboard.keysUp;
  43782. return [];
  43783. },
  43784. set: function (value) {
  43785. var keyboard = this.inputs.attached["keyboard"];
  43786. if (keyboard)
  43787. keyboard.keysUp = value;
  43788. },
  43789. enumerable: true,
  43790. configurable: true
  43791. });
  43792. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43793. get: function () {
  43794. var keyboard = this.inputs.attached["keyboard"];
  43795. if (keyboard)
  43796. return keyboard.keysDown;
  43797. return [];
  43798. },
  43799. set: function (value) {
  43800. var keyboard = this.inputs.attached["keyboard"];
  43801. if (keyboard)
  43802. keyboard.keysDown = value;
  43803. },
  43804. enumerable: true,
  43805. configurable: true
  43806. });
  43807. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43808. get: function () {
  43809. var keyboard = this.inputs.attached["keyboard"];
  43810. if (keyboard)
  43811. return keyboard.keysLeft;
  43812. return [];
  43813. },
  43814. set: function (value) {
  43815. var keyboard = this.inputs.attached["keyboard"];
  43816. if (keyboard)
  43817. keyboard.keysLeft = value;
  43818. },
  43819. enumerable: true,
  43820. configurable: true
  43821. });
  43822. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43823. get: function () {
  43824. var keyboard = this.inputs.attached["keyboard"];
  43825. if (keyboard)
  43826. return keyboard.keysRight;
  43827. return [];
  43828. },
  43829. set: function (value) {
  43830. var keyboard = this.inputs.attached["keyboard"];
  43831. if (keyboard)
  43832. keyboard.keysRight = value;
  43833. },
  43834. enumerable: true,
  43835. configurable: true
  43836. });
  43837. // Controls
  43838. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43839. this.inputs.attachElement(element, noPreventDefault);
  43840. };
  43841. FreeCamera.prototype.detachControl = function (element) {
  43842. this.inputs.detachElement(element);
  43843. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43844. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43845. };
  43846. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43847. get: function () {
  43848. return this._collisionMask;
  43849. },
  43850. set: function (mask) {
  43851. this._collisionMask = !isNaN(mask) ? mask : -1;
  43852. },
  43853. enumerable: true,
  43854. configurable: true
  43855. });
  43856. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43857. var globalPosition;
  43858. if (this.parent) {
  43859. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43860. }
  43861. else {
  43862. globalPosition = this.position;
  43863. }
  43864. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43865. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43866. if (!this._collider) {
  43867. this._collider = new BABYLON.Collider();
  43868. }
  43869. this._collider._radius = this.ellipsoid;
  43870. this._collider.collisionMask = this._collisionMask;
  43871. //no need for clone, as long as gravity is not on.
  43872. var actualDisplacement = displacement;
  43873. //add gravity to the direction to prevent the dual-collision checking
  43874. if (this.applyGravity) {
  43875. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43876. actualDisplacement = displacement.add(this.getScene().gravity);
  43877. }
  43878. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43879. };
  43880. FreeCamera.prototype._checkInputs = function () {
  43881. if (!this._localDirection) {
  43882. this._localDirection = BABYLON.Vector3.Zero();
  43883. this._transformedDirection = BABYLON.Vector3.Zero();
  43884. }
  43885. this.inputs.checkInputs();
  43886. _super.prototype._checkInputs.call(this);
  43887. };
  43888. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43889. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43890. };
  43891. FreeCamera.prototype._updatePosition = function () {
  43892. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43893. this._collideWithWorld(this.cameraDirection);
  43894. }
  43895. else {
  43896. _super.prototype._updatePosition.call(this);
  43897. }
  43898. };
  43899. FreeCamera.prototype.dispose = function () {
  43900. this.inputs.clear();
  43901. _super.prototype.dispose.call(this);
  43902. };
  43903. FreeCamera.prototype.getClassName = function () {
  43904. return "FreeCamera";
  43905. };
  43906. __decorate([
  43907. BABYLON.serializeAsVector3()
  43908. ], FreeCamera.prototype, "ellipsoid", void 0);
  43909. __decorate([
  43910. BABYLON.serializeAsVector3()
  43911. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43912. __decorate([
  43913. BABYLON.serialize()
  43914. ], FreeCamera.prototype, "checkCollisions", void 0);
  43915. __decorate([
  43916. BABYLON.serialize()
  43917. ], FreeCamera.prototype, "applyGravity", void 0);
  43918. return FreeCamera;
  43919. }(BABYLON.TargetCamera));
  43920. BABYLON.FreeCamera = FreeCamera;
  43921. })(BABYLON || (BABYLON = {}));
  43922. //# sourceMappingURL=babylon.freeCamera.js.map
  43923. var BABYLON;
  43924. (function (BABYLON) {
  43925. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43926. function ArcRotateCameraKeyboardMoveInput() {
  43927. this._keys = new Array();
  43928. this.keysUp = [38];
  43929. this.keysDown = [40];
  43930. this.keysLeft = [37];
  43931. this.keysRight = [39];
  43932. this.keysReset = [220];
  43933. this.panningSensibility = 50.0;
  43934. this.zoomingSensibility = 25.0;
  43935. this.useAltToZoom = true;
  43936. }
  43937. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43938. var _this = this;
  43939. if (this._onCanvasBlurObserver) {
  43940. return;
  43941. }
  43942. this._scene = this.camera.getScene();
  43943. this._engine = this._scene.getEngine();
  43944. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43945. _this._keys = [];
  43946. });
  43947. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43948. var evt = info.event;
  43949. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43950. _this._ctrlPressed = evt.ctrlKey;
  43951. _this._altPressed = evt.altKey;
  43952. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43953. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43954. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43955. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43956. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43957. var index = _this._keys.indexOf(evt.keyCode);
  43958. if (index === -1) {
  43959. _this._keys.push(evt.keyCode);
  43960. }
  43961. if (evt.preventDefault) {
  43962. if (!noPreventDefault) {
  43963. evt.preventDefault();
  43964. }
  43965. }
  43966. }
  43967. }
  43968. else {
  43969. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43970. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43971. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43972. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43973. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43974. var index = _this._keys.indexOf(evt.keyCode);
  43975. if (index >= 0) {
  43976. _this._keys.splice(index, 1);
  43977. }
  43978. if (evt.preventDefault) {
  43979. if (!noPreventDefault) {
  43980. evt.preventDefault();
  43981. }
  43982. }
  43983. }
  43984. }
  43985. });
  43986. };
  43987. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43988. if (this._scene) {
  43989. if (this._onKeyboardObserver) {
  43990. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43991. }
  43992. if (this._onCanvasBlurObserver) {
  43993. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43994. }
  43995. this._onKeyboardObserver = null;
  43996. this._onCanvasBlurObserver = null;
  43997. }
  43998. this._keys = [];
  43999. };
  44000. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44001. if (this._onKeyboardObserver) {
  44002. var camera = this.camera;
  44003. for (var index = 0; index < this._keys.length; index++) {
  44004. var keyCode = this._keys[index];
  44005. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44006. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44007. camera.inertialPanningX -= 1 / this.panningSensibility;
  44008. }
  44009. else {
  44010. camera.inertialAlphaOffset -= 0.01;
  44011. }
  44012. }
  44013. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44014. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44015. camera.inertialPanningY += 1 / this.panningSensibility;
  44016. }
  44017. else if (this._altPressed && this.useAltToZoom) {
  44018. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44019. }
  44020. else {
  44021. camera.inertialBetaOffset -= 0.01;
  44022. }
  44023. }
  44024. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44025. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44026. camera.inertialPanningX += 1 / this.panningSensibility;
  44027. }
  44028. else {
  44029. camera.inertialAlphaOffset += 0.01;
  44030. }
  44031. }
  44032. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44033. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44034. camera.inertialPanningY -= 1 / this.panningSensibility;
  44035. }
  44036. else if (this._altPressed && this.useAltToZoom) {
  44037. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44038. }
  44039. else {
  44040. camera.inertialBetaOffset += 0.01;
  44041. }
  44042. }
  44043. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44044. camera.restoreState();
  44045. }
  44046. }
  44047. }
  44048. };
  44049. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44050. return "ArcRotateCameraKeyboardMoveInput";
  44051. };
  44052. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44053. return "keyboard";
  44054. };
  44055. __decorate([
  44056. BABYLON.serialize()
  44057. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44058. __decorate([
  44059. BABYLON.serialize()
  44060. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44061. __decorate([
  44062. BABYLON.serialize()
  44063. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44064. __decorate([
  44065. BABYLON.serialize()
  44066. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44067. __decorate([
  44068. BABYLON.serialize()
  44069. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44070. __decorate([
  44071. BABYLON.serialize()
  44072. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44073. __decorate([
  44074. BABYLON.serialize()
  44075. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44076. __decorate([
  44077. BABYLON.serialize()
  44078. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44079. return ArcRotateCameraKeyboardMoveInput;
  44080. }());
  44081. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44082. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44083. })(BABYLON || (BABYLON = {}));
  44084. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44085. var BABYLON;
  44086. (function (BABYLON) {
  44087. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44088. function ArcRotateCameraMouseWheelInput() {
  44089. this.wheelPrecision = 3.0;
  44090. /**
  44091. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44092. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44093. */
  44094. this.wheelDeltaPercentage = 0;
  44095. }
  44096. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44097. var _this = this;
  44098. this._wheel = function (p, s) {
  44099. //sanity check - this should be a PointerWheel event.
  44100. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44101. return;
  44102. var event = p.event;
  44103. var delta = 0;
  44104. if (event.wheelDelta) {
  44105. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44106. }
  44107. else if (event.detail) {
  44108. delta = -event.detail / _this.wheelPrecision;
  44109. }
  44110. if (delta)
  44111. _this.camera.inertialRadiusOffset += delta;
  44112. if (event.preventDefault) {
  44113. if (!noPreventDefault) {
  44114. event.preventDefault();
  44115. }
  44116. }
  44117. };
  44118. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44119. };
  44120. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44121. if (this._observer && element) {
  44122. this.camera.getScene().onPointerObservable.remove(this._observer);
  44123. this._observer = null;
  44124. this._wheel = null;
  44125. }
  44126. };
  44127. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44128. return "ArcRotateCameraMouseWheelInput";
  44129. };
  44130. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44131. return "mousewheel";
  44132. };
  44133. __decorate([
  44134. BABYLON.serialize()
  44135. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44136. __decorate([
  44137. BABYLON.serialize()
  44138. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44139. return ArcRotateCameraMouseWheelInput;
  44140. }());
  44141. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44142. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44143. })(BABYLON || (BABYLON = {}));
  44144. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44145. var BABYLON;
  44146. (function (BABYLON) {
  44147. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44148. function ArcRotateCameraPointersInput() {
  44149. this.buttons = [0, 1, 2];
  44150. this.angularSensibilityX = 1000.0;
  44151. this.angularSensibilityY = 1000.0;
  44152. this.pinchPrecision = 12.0;
  44153. /**
  44154. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44155. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44156. */
  44157. this.pinchDeltaPercentage = 0;
  44158. this.panningSensibility = 1000.0;
  44159. this.multiTouchPanning = true;
  44160. this.multiTouchPanAndZoom = true;
  44161. this._isPanClick = false;
  44162. this.pinchInwards = true;
  44163. }
  44164. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44165. var _this = this;
  44166. var engine = this.camera.getEngine();
  44167. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44168. var pointA = null;
  44169. var pointB = null;
  44170. var previousPinchSquaredDistance = 0;
  44171. var initialDistance = 0;
  44172. var twoFingerActivityCount = 0;
  44173. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44174. this._pointerInput = function (p, s) {
  44175. var evt = p.event;
  44176. var isTouch = p.event.pointerType === "touch";
  44177. if (engine.isInVRExclusivePointerMode) {
  44178. return;
  44179. }
  44180. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44181. return;
  44182. }
  44183. var srcElement = (evt.srcElement || evt.target);
  44184. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44185. try {
  44186. srcElement.setPointerCapture(evt.pointerId);
  44187. }
  44188. catch (e) {
  44189. //Nothing to do with the error. Execution will continue.
  44190. }
  44191. // Manage panning with pan button click
  44192. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44193. // manage pointers
  44194. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44195. if (pointA === null) {
  44196. pointA = cacheSoloPointer;
  44197. }
  44198. else if (pointB === null) {
  44199. pointB = cacheSoloPointer;
  44200. }
  44201. if (!noPreventDefault) {
  44202. evt.preventDefault();
  44203. element.focus();
  44204. }
  44205. }
  44206. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44207. _this.camera.restoreState();
  44208. }
  44209. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44210. try {
  44211. srcElement.releasePointerCapture(evt.pointerId);
  44212. }
  44213. catch (e) {
  44214. //Nothing to do with the error.
  44215. }
  44216. cacheSoloPointer = null;
  44217. previousPinchSquaredDistance = 0;
  44218. previousMultiTouchPanPosition.isPaning = false;
  44219. previousMultiTouchPanPosition.isPinching = false;
  44220. twoFingerActivityCount = 0;
  44221. initialDistance = 0;
  44222. if (!isTouch) {
  44223. pointB = null; // Mouse and pen are mono pointer
  44224. }
  44225. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44226. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44227. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44228. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44229. if (engine.badOS) {
  44230. pointA = pointB = null;
  44231. }
  44232. else {
  44233. //only remove the impacted pointer in case of multitouch allowing on most
  44234. //platforms switching from rotate to zoom and pan seamlessly.
  44235. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44236. pointA = pointB;
  44237. pointB = null;
  44238. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44239. }
  44240. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44241. pointB = null;
  44242. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44243. }
  44244. else {
  44245. pointA = pointB = null;
  44246. }
  44247. }
  44248. if (!noPreventDefault) {
  44249. evt.preventDefault();
  44250. }
  44251. }
  44252. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44253. if (!noPreventDefault) {
  44254. evt.preventDefault();
  44255. }
  44256. // One button down
  44257. if (pointA && pointB === null && cacheSoloPointer) {
  44258. if (_this.panningSensibility !== 0 &&
  44259. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44260. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44261. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44262. }
  44263. else {
  44264. var offsetX = evt.clientX - cacheSoloPointer.x;
  44265. var offsetY = evt.clientY - cacheSoloPointer.y;
  44266. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44267. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44268. }
  44269. cacheSoloPointer.x = evt.clientX;
  44270. cacheSoloPointer.y = evt.clientY;
  44271. }
  44272. else if (pointA && pointB) {
  44273. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44274. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44275. ed.x = evt.clientX;
  44276. ed.y = evt.clientY;
  44277. var direction = _this.pinchInwards ? 1 : -1;
  44278. var distX = pointA.x - pointB.x;
  44279. var distY = pointA.y - pointB.y;
  44280. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44281. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44282. if (previousPinchSquaredDistance === 0) {
  44283. initialDistance = pinchDistance;
  44284. previousPinchSquaredDistance = pinchSquaredDistance;
  44285. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44286. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44287. return;
  44288. }
  44289. if (_this.multiTouchPanAndZoom) {
  44290. if (_this.pinchDeltaPercentage) {
  44291. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44292. }
  44293. else {
  44294. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44295. (_this.pinchPrecision *
  44296. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44297. direction);
  44298. }
  44299. if (_this.panningSensibility !== 0) {
  44300. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44301. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44302. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44303. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44304. previousMultiTouchPanPosition.x = pointersCenterX;
  44305. previousMultiTouchPanPosition.y = pointersCenterY;
  44306. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44307. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44308. }
  44309. }
  44310. else {
  44311. twoFingerActivityCount++;
  44312. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44313. if (_this.pinchDeltaPercentage) {
  44314. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44315. }
  44316. else {
  44317. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44318. (_this.pinchPrecision *
  44319. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44320. direction);
  44321. }
  44322. previousMultiTouchPanPosition.isPaning = false;
  44323. previousMultiTouchPanPosition.isPinching = true;
  44324. }
  44325. else {
  44326. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44327. if (!previousMultiTouchPanPosition.isPaning) {
  44328. previousMultiTouchPanPosition.isPaning = true;
  44329. previousMultiTouchPanPosition.isPinching = false;
  44330. previousMultiTouchPanPosition.x = ed.x;
  44331. previousMultiTouchPanPosition.y = ed.y;
  44332. return;
  44333. }
  44334. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44335. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44336. }
  44337. }
  44338. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44339. previousMultiTouchPanPosition.x = ed.x;
  44340. previousMultiTouchPanPosition.y = ed.y;
  44341. }
  44342. }
  44343. previousPinchSquaredDistance = pinchSquaredDistance;
  44344. }
  44345. }
  44346. };
  44347. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44348. this._onContextMenu = function (evt) {
  44349. evt.preventDefault();
  44350. };
  44351. if (!this.camera._useCtrlForPanning) {
  44352. element.addEventListener("contextmenu", this._onContextMenu, false);
  44353. }
  44354. this._onLostFocus = function () {
  44355. //this._keys = [];
  44356. pointA = pointB = null;
  44357. previousPinchSquaredDistance = 0;
  44358. previousMultiTouchPanPosition.isPaning = false;
  44359. previousMultiTouchPanPosition.isPinching = false;
  44360. twoFingerActivityCount = 0;
  44361. cacheSoloPointer = null;
  44362. initialDistance = 0;
  44363. };
  44364. this._onMouseMove = function (evt) {
  44365. if (!engine.isPointerLock) {
  44366. return;
  44367. }
  44368. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44369. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44370. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44371. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44372. if (!noPreventDefault) {
  44373. evt.preventDefault();
  44374. }
  44375. };
  44376. this._onGestureStart = function (e) {
  44377. if (window.MSGesture === undefined) {
  44378. return;
  44379. }
  44380. if (!_this._MSGestureHandler) {
  44381. _this._MSGestureHandler = new MSGesture();
  44382. _this._MSGestureHandler.target = element;
  44383. }
  44384. _this._MSGestureHandler.addPointer(e.pointerId);
  44385. };
  44386. this._onGesture = function (e) {
  44387. _this.camera.radius *= e.scale;
  44388. if (e.preventDefault) {
  44389. if (!noPreventDefault) {
  44390. e.stopPropagation();
  44391. e.preventDefault();
  44392. }
  44393. }
  44394. };
  44395. element.addEventListener("mousemove", this._onMouseMove, false);
  44396. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44397. element.addEventListener("MSGestureChange", this._onGesture, false);
  44398. BABYLON.Tools.RegisterTopRootEvents([
  44399. { name: "blur", handler: this._onLostFocus }
  44400. ]);
  44401. };
  44402. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44403. if (this._onLostFocus) {
  44404. BABYLON.Tools.UnregisterTopRootEvents([
  44405. { name: "blur", handler: this._onLostFocus }
  44406. ]);
  44407. }
  44408. if (element && this._observer) {
  44409. this.camera.getScene().onPointerObservable.remove(this._observer);
  44410. this._observer = null;
  44411. if (this._onContextMenu) {
  44412. element.removeEventListener("contextmenu", this._onContextMenu);
  44413. }
  44414. if (this._onMouseMove) {
  44415. element.removeEventListener("mousemove", this._onMouseMove);
  44416. }
  44417. if (this._onGestureStart) {
  44418. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44419. }
  44420. if (this._onGesture) {
  44421. element.removeEventListener("MSGestureChange", this._onGesture);
  44422. }
  44423. this._isPanClick = false;
  44424. this.pinchInwards = true;
  44425. this._onMouseMove = null;
  44426. this._onGestureStart = null;
  44427. this._onGesture = null;
  44428. this._MSGestureHandler = null;
  44429. this._onLostFocus = null;
  44430. this._onContextMenu = null;
  44431. }
  44432. };
  44433. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44434. return "ArcRotateCameraPointersInput";
  44435. };
  44436. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44437. return "pointers";
  44438. };
  44439. __decorate([
  44440. BABYLON.serialize()
  44441. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44442. __decorate([
  44443. BABYLON.serialize()
  44444. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44445. __decorate([
  44446. BABYLON.serialize()
  44447. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44448. __decorate([
  44449. BABYLON.serialize()
  44450. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44451. __decorate([
  44452. BABYLON.serialize()
  44453. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44454. __decorate([
  44455. BABYLON.serialize()
  44456. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44457. __decorate([
  44458. BABYLON.serialize()
  44459. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44460. __decorate([
  44461. BABYLON.serialize()
  44462. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44463. return ArcRotateCameraPointersInput;
  44464. }());
  44465. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44466. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44467. })(BABYLON || (BABYLON = {}));
  44468. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44469. var BABYLON;
  44470. (function (BABYLON) {
  44471. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44472. __extends(ArcRotateCameraInputsManager, _super);
  44473. function ArcRotateCameraInputsManager(camera) {
  44474. return _super.call(this, camera) || this;
  44475. }
  44476. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44477. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44478. return this;
  44479. };
  44480. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44481. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44482. return this;
  44483. };
  44484. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44485. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44486. return this;
  44487. };
  44488. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44489. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44490. return this;
  44491. };
  44492. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44493. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44494. return this;
  44495. };
  44496. return ArcRotateCameraInputsManager;
  44497. }(BABYLON.CameraInputsManager));
  44498. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44499. })(BABYLON || (BABYLON = {}));
  44500. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44501. var BABYLON;
  44502. (function (BABYLON) {
  44503. var ArcRotateCamera = /** @class */ (function (_super) {
  44504. __extends(ArcRotateCamera, _super);
  44505. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44506. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44507. _this.inertialAlphaOffset = 0;
  44508. _this.inertialBetaOffset = 0;
  44509. _this.inertialRadiusOffset = 0;
  44510. _this.lowerAlphaLimit = null;
  44511. _this.upperAlphaLimit = null;
  44512. _this.lowerBetaLimit = 0.01;
  44513. _this.upperBetaLimit = Math.PI;
  44514. _this.lowerRadiusLimit = null;
  44515. _this.upperRadiusLimit = null;
  44516. _this.inertialPanningX = 0;
  44517. _this.inertialPanningY = 0;
  44518. _this.pinchToPanMaxDistance = 20;
  44519. _this.panningDistanceLimit = null;
  44520. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44521. _this.panningInertia = 0.9;
  44522. //-- end properties for backward compatibility for inputs
  44523. _this.zoomOnFactor = 1;
  44524. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44525. _this.allowUpsideDown = true;
  44526. _this._viewMatrix = new BABYLON.Matrix();
  44527. // Panning
  44528. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44529. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44530. _this.checkCollisions = false;
  44531. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44532. _this._previousPosition = BABYLON.Vector3.Zero();
  44533. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44534. _this._newPosition = BABYLON.Vector3.Zero();
  44535. _this._computationVector = BABYLON.Vector3.Zero();
  44536. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44537. if (collidedMesh === void 0) { collidedMesh = null; }
  44538. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44539. newPosition.multiplyInPlace(_this._collider._radius);
  44540. }
  44541. if (!collidedMesh) {
  44542. _this._previousPosition.copyFrom(_this.position);
  44543. }
  44544. else {
  44545. _this.setPosition(newPosition);
  44546. if (_this.onCollide) {
  44547. _this.onCollide(collidedMesh);
  44548. }
  44549. }
  44550. // Recompute because of constraints
  44551. var cosa = Math.cos(_this.alpha);
  44552. var sina = Math.sin(_this.alpha);
  44553. var cosb = Math.cos(_this.beta);
  44554. var sinb = Math.sin(_this.beta);
  44555. if (sinb === 0) {
  44556. sinb = 0.0001;
  44557. }
  44558. var target = _this._getTargetPosition();
  44559. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44560. target.addToRef(_this._computationVector, _this._newPosition);
  44561. _this.position.copyFrom(_this._newPosition);
  44562. var up = _this.upVector;
  44563. if (_this.allowUpsideDown && _this.beta < 0) {
  44564. up = up.clone();
  44565. up = up.negate();
  44566. }
  44567. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44568. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44569. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44570. _this._collisionTriggered = false;
  44571. };
  44572. _this._target = BABYLON.Vector3.Zero();
  44573. if (target) {
  44574. _this.setTarget(target);
  44575. }
  44576. _this.alpha = alpha;
  44577. _this.beta = beta;
  44578. _this.radius = radius;
  44579. _this.getViewMatrix();
  44580. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44581. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44582. return _this;
  44583. }
  44584. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44585. get: function () {
  44586. return this._target;
  44587. },
  44588. set: function (value) {
  44589. this.setTarget(value);
  44590. },
  44591. enumerable: true,
  44592. configurable: true
  44593. });
  44594. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44595. //-- begin properties for backward compatibility for inputs
  44596. get: function () {
  44597. var pointers = this.inputs.attached["pointers"];
  44598. if (pointers)
  44599. return pointers.angularSensibilityX;
  44600. return 0;
  44601. },
  44602. set: function (value) {
  44603. var pointers = this.inputs.attached["pointers"];
  44604. if (pointers) {
  44605. pointers.angularSensibilityX = value;
  44606. }
  44607. },
  44608. enumerable: true,
  44609. configurable: true
  44610. });
  44611. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44612. get: function () {
  44613. var pointers = this.inputs.attached["pointers"];
  44614. if (pointers)
  44615. return pointers.angularSensibilityY;
  44616. return 0;
  44617. },
  44618. set: function (value) {
  44619. var pointers = this.inputs.attached["pointers"];
  44620. if (pointers) {
  44621. pointers.angularSensibilityY = value;
  44622. }
  44623. },
  44624. enumerable: true,
  44625. configurable: true
  44626. });
  44627. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44628. get: function () {
  44629. var pointers = this.inputs.attached["pointers"];
  44630. if (pointers)
  44631. return pointers.pinchPrecision;
  44632. return 0;
  44633. },
  44634. set: function (value) {
  44635. var pointers = this.inputs.attached["pointers"];
  44636. if (pointers) {
  44637. pointers.pinchPrecision = value;
  44638. }
  44639. },
  44640. enumerable: true,
  44641. configurable: true
  44642. });
  44643. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44644. get: function () {
  44645. var pointers = this.inputs.attached["pointers"];
  44646. if (pointers)
  44647. return pointers.pinchDeltaPercentage;
  44648. return 0;
  44649. },
  44650. set: function (value) {
  44651. var pointers = this.inputs.attached["pointers"];
  44652. if (pointers) {
  44653. pointers.pinchDeltaPercentage = value;
  44654. }
  44655. },
  44656. enumerable: true,
  44657. configurable: true
  44658. });
  44659. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44660. get: function () {
  44661. var pointers = this.inputs.attached["pointers"];
  44662. if (pointers)
  44663. return pointers.panningSensibility;
  44664. return 0;
  44665. },
  44666. set: function (value) {
  44667. var pointers = this.inputs.attached["pointers"];
  44668. if (pointers) {
  44669. pointers.panningSensibility = value;
  44670. }
  44671. },
  44672. enumerable: true,
  44673. configurable: true
  44674. });
  44675. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44676. get: function () {
  44677. var keyboard = this.inputs.attached["keyboard"];
  44678. if (keyboard)
  44679. return keyboard.keysUp;
  44680. return [];
  44681. },
  44682. set: function (value) {
  44683. var keyboard = this.inputs.attached["keyboard"];
  44684. if (keyboard)
  44685. keyboard.keysUp = value;
  44686. },
  44687. enumerable: true,
  44688. configurable: true
  44689. });
  44690. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44691. get: function () {
  44692. var keyboard = this.inputs.attached["keyboard"];
  44693. if (keyboard)
  44694. return keyboard.keysDown;
  44695. return [];
  44696. },
  44697. set: function (value) {
  44698. var keyboard = this.inputs.attached["keyboard"];
  44699. if (keyboard)
  44700. keyboard.keysDown = value;
  44701. },
  44702. enumerable: true,
  44703. configurable: true
  44704. });
  44705. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44706. get: function () {
  44707. var keyboard = this.inputs.attached["keyboard"];
  44708. if (keyboard)
  44709. return keyboard.keysLeft;
  44710. return [];
  44711. },
  44712. set: function (value) {
  44713. var keyboard = this.inputs.attached["keyboard"];
  44714. if (keyboard)
  44715. keyboard.keysLeft = value;
  44716. },
  44717. enumerable: true,
  44718. configurable: true
  44719. });
  44720. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44721. get: function () {
  44722. var keyboard = this.inputs.attached["keyboard"];
  44723. if (keyboard)
  44724. return keyboard.keysRight;
  44725. return [];
  44726. },
  44727. set: function (value) {
  44728. var keyboard = this.inputs.attached["keyboard"];
  44729. if (keyboard)
  44730. keyboard.keysRight = value;
  44731. },
  44732. enumerable: true,
  44733. configurable: true
  44734. });
  44735. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44736. get: function () {
  44737. var mousewheel = this.inputs.attached["mousewheel"];
  44738. if (mousewheel)
  44739. return mousewheel.wheelPrecision;
  44740. return 0;
  44741. },
  44742. set: function (value) {
  44743. var mousewheel = this.inputs.attached["mousewheel"];
  44744. if (mousewheel)
  44745. mousewheel.wheelPrecision = value;
  44746. },
  44747. enumerable: true,
  44748. configurable: true
  44749. });
  44750. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44751. get: function () {
  44752. var mousewheel = this.inputs.attached["mousewheel"];
  44753. if (mousewheel)
  44754. return mousewheel.wheelDeltaPercentage;
  44755. return 0;
  44756. },
  44757. set: function (value) {
  44758. var mousewheel = this.inputs.attached["mousewheel"];
  44759. if (mousewheel)
  44760. mousewheel.wheelDeltaPercentage = value;
  44761. },
  44762. enumerable: true,
  44763. configurable: true
  44764. });
  44765. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44766. get: function () {
  44767. return this._bouncingBehavior;
  44768. },
  44769. enumerable: true,
  44770. configurable: true
  44771. });
  44772. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44773. get: function () {
  44774. return this._bouncingBehavior != null;
  44775. },
  44776. set: function (value) {
  44777. if (value === this.useBouncingBehavior) {
  44778. return;
  44779. }
  44780. if (value) {
  44781. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44782. this.addBehavior(this._bouncingBehavior);
  44783. }
  44784. else if (this._bouncingBehavior) {
  44785. this.removeBehavior(this._bouncingBehavior);
  44786. this._bouncingBehavior = null;
  44787. }
  44788. },
  44789. enumerable: true,
  44790. configurable: true
  44791. });
  44792. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44793. get: function () {
  44794. return this._framingBehavior;
  44795. },
  44796. enumerable: true,
  44797. configurable: true
  44798. });
  44799. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44800. get: function () {
  44801. return this._framingBehavior != null;
  44802. },
  44803. set: function (value) {
  44804. if (value === this.useFramingBehavior) {
  44805. return;
  44806. }
  44807. if (value) {
  44808. this._framingBehavior = new BABYLON.FramingBehavior();
  44809. this.addBehavior(this._framingBehavior);
  44810. }
  44811. else if (this._framingBehavior) {
  44812. this.removeBehavior(this._framingBehavior);
  44813. this._framingBehavior = null;
  44814. }
  44815. },
  44816. enumerable: true,
  44817. configurable: true
  44818. });
  44819. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44820. get: function () {
  44821. return this._autoRotationBehavior;
  44822. },
  44823. enumerable: true,
  44824. configurable: true
  44825. });
  44826. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44827. get: function () {
  44828. return this._autoRotationBehavior != null;
  44829. },
  44830. set: function (value) {
  44831. if (value === this.useAutoRotationBehavior) {
  44832. return;
  44833. }
  44834. if (value) {
  44835. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44836. this.addBehavior(this._autoRotationBehavior);
  44837. }
  44838. else if (this._autoRotationBehavior) {
  44839. this.removeBehavior(this._autoRotationBehavior);
  44840. this._autoRotationBehavior = null;
  44841. }
  44842. },
  44843. enumerable: true,
  44844. configurable: true
  44845. });
  44846. // Cache
  44847. ArcRotateCamera.prototype._initCache = function () {
  44848. _super.prototype._initCache.call(this);
  44849. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44850. this._cache.alpha = undefined;
  44851. this._cache.beta = undefined;
  44852. this._cache.radius = undefined;
  44853. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44854. };
  44855. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44856. if (!ignoreParentClass) {
  44857. _super.prototype._updateCache.call(this);
  44858. }
  44859. this._cache._target.copyFrom(this._getTargetPosition());
  44860. this._cache.alpha = this.alpha;
  44861. this._cache.beta = this.beta;
  44862. this._cache.radius = this.radius;
  44863. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44864. };
  44865. ArcRotateCamera.prototype._getTargetPosition = function () {
  44866. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44867. var pos = this._targetHost.getAbsolutePosition();
  44868. if (this._targetBoundingCenter) {
  44869. pos.addToRef(this._targetBoundingCenter, this._target);
  44870. }
  44871. else {
  44872. this._target.copyFrom(pos);
  44873. }
  44874. }
  44875. var lockedTargetPosition = this._getLockedTargetPosition();
  44876. if (lockedTargetPosition) {
  44877. return lockedTargetPosition;
  44878. }
  44879. return this._target;
  44880. };
  44881. ArcRotateCamera.prototype.storeState = function () {
  44882. this._storedAlpha = this.alpha;
  44883. this._storedBeta = this.beta;
  44884. this._storedRadius = this.radius;
  44885. this._storedTarget = this._getTargetPosition().clone();
  44886. return _super.prototype.storeState.call(this);
  44887. };
  44888. /**
  44889. * Restored camera state. You must call storeState() first
  44890. */
  44891. ArcRotateCamera.prototype._restoreStateValues = function () {
  44892. if (!_super.prototype._restoreStateValues.call(this)) {
  44893. return false;
  44894. }
  44895. this.alpha = this._storedAlpha;
  44896. this.beta = this._storedBeta;
  44897. this.radius = this._storedRadius;
  44898. this.setTarget(this._storedTarget.clone());
  44899. this.inertialAlphaOffset = 0;
  44900. this.inertialBetaOffset = 0;
  44901. this.inertialRadiusOffset = 0;
  44902. this.inertialPanningX = 0;
  44903. this.inertialPanningY = 0;
  44904. return true;
  44905. };
  44906. // Synchronized
  44907. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44908. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44909. return false;
  44910. return this._cache._target.equals(this._getTargetPosition())
  44911. && this._cache.alpha === this.alpha
  44912. && this._cache.beta === this.beta
  44913. && this._cache.radius === this.radius
  44914. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44915. };
  44916. // Methods
  44917. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44918. var _this = this;
  44919. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44920. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44921. this._useCtrlForPanning = useCtrlForPanning;
  44922. this._panningMouseButton = panningMouseButton;
  44923. this.inputs.attachElement(element, noPreventDefault);
  44924. this._reset = function () {
  44925. _this.inertialAlphaOffset = 0;
  44926. _this.inertialBetaOffset = 0;
  44927. _this.inertialRadiusOffset = 0;
  44928. _this.inertialPanningX = 0;
  44929. _this.inertialPanningY = 0;
  44930. };
  44931. };
  44932. ArcRotateCamera.prototype.detachControl = function (element) {
  44933. this.inputs.detachElement(element);
  44934. if (this._reset) {
  44935. this._reset();
  44936. }
  44937. };
  44938. ArcRotateCamera.prototype._checkInputs = function () {
  44939. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44940. if (this._collisionTriggered) {
  44941. return;
  44942. }
  44943. this.inputs.checkInputs();
  44944. // Inertia
  44945. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44946. if (this.getScene().useRightHandedSystem) {
  44947. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44948. }
  44949. else {
  44950. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44951. }
  44952. this.beta += this.inertialBetaOffset;
  44953. this.radius -= this.inertialRadiusOffset;
  44954. this.inertialAlphaOffset *= this.inertia;
  44955. this.inertialBetaOffset *= this.inertia;
  44956. this.inertialRadiusOffset *= this.inertia;
  44957. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44958. this.inertialAlphaOffset = 0;
  44959. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44960. this.inertialBetaOffset = 0;
  44961. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44962. this.inertialRadiusOffset = 0;
  44963. }
  44964. // Panning inertia
  44965. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44966. if (!this._localDirection) {
  44967. this._localDirection = BABYLON.Vector3.Zero();
  44968. this._transformedDirection = BABYLON.Vector3.Zero();
  44969. }
  44970. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44971. this._localDirection.multiplyInPlace(this.panningAxis);
  44972. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44973. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44974. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44975. if (!this.panningAxis.y) {
  44976. this._transformedDirection.y = 0;
  44977. }
  44978. if (!this._targetHost) {
  44979. if (this.panningDistanceLimit) {
  44980. this._transformedDirection.addInPlace(this._target);
  44981. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44982. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44983. this._target.copyFrom(this._transformedDirection);
  44984. }
  44985. }
  44986. else {
  44987. this._target.addInPlace(this._transformedDirection);
  44988. }
  44989. }
  44990. this.inertialPanningX *= this.panningInertia;
  44991. this.inertialPanningY *= this.panningInertia;
  44992. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44993. this.inertialPanningX = 0;
  44994. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44995. this.inertialPanningY = 0;
  44996. }
  44997. // Limits
  44998. this._checkLimits();
  44999. _super.prototype._checkInputs.call(this);
  45000. };
  45001. ArcRotateCamera.prototype._checkLimits = function () {
  45002. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45003. if (this.allowUpsideDown && this.beta > Math.PI) {
  45004. this.beta = this.beta - (2 * Math.PI);
  45005. }
  45006. }
  45007. else {
  45008. if (this.beta < this.lowerBetaLimit) {
  45009. this.beta = this.lowerBetaLimit;
  45010. }
  45011. }
  45012. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45013. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45014. this.beta = this.beta + (2 * Math.PI);
  45015. }
  45016. }
  45017. else {
  45018. if (this.beta > this.upperBetaLimit) {
  45019. this.beta = this.upperBetaLimit;
  45020. }
  45021. }
  45022. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45023. this.alpha = this.lowerAlphaLimit;
  45024. }
  45025. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45026. this.alpha = this.upperAlphaLimit;
  45027. }
  45028. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45029. this.radius = this.lowerRadiusLimit;
  45030. }
  45031. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45032. this.radius = this.upperRadiusLimit;
  45033. }
  45034. };
  45035. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45036. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45037. this.radius = this._computationVector.length();
  45038. if (this.radius === 0) {
  45039. this.radius = 0.0001; // Just to avoid division by zero
  45040. }
  45041. // Alpha
  45042. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45043. if (this._computationVector.z < 0) {
  45044. this.alpha = 2 * Math.PI - this.alpha;
  45045. }
  45046. // Beta
  45047. this.beta = Math.acos(this._computationVector.y / this.radius);
  45048. this._checkLimits();
  45049. };
  45050. ArcRotateCamera.prototype.setPosition = function (position) {
  45051. if (this.position.equals(position)) {
  45052. return;
  45053. }
  45054. this.position.copyFrom(position);
  45055. this.rebuildAnglesAndRadius();
  45056. };
  45057. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45058. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45059. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45060. if (target.getBoundingInfo) {
  45061. if (toBoundingCenter) {
  45062. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45063. }
  45064. else {
  45065. this._targetBoundingCenter = null;
  45066. }
  45067. this._targetHost = target;
  45068. this._target = this._getTargetPosition();
  45069. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45070. }
  45071. else {
  45072. var newTarget = target;
  45073. var currentTarget = this._getTargetPosition();
  45074. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45075. return;
  45076. }
  45077. this._targetHost = null;
  45078. this._target = newTarget;
  45079. this._targetBoundingCenter = null;
  45080. this.onMeshTargetChangedObservable.notifyObservers(null);
  45081. }
  45082. this.rebuildAnglesAndRadius();
  45083. };
  45084. ArcRotateCamera.prototype._getViewMatrix = function () {
  45085. // Compute
  45086. var cosa = Math.cos(this.alpha);
  45087. var sina = Math.sin(this.alpha);
  45088. var cosb = Math.cos(this.beta);
  45089. var sinb = Math.sin(this.beta);
  45090. if (sinb === 0) {
  45091. sinb = 0.0001;
  45092. }
  45093. var target = this._getTargetPosition();
  45094. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45095. target.addToRef(this._computationVector, this._newPosition);
  45096. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45097. if (!this._collider) {
  45098. this._collider = new BABYLON.Collider();
  45099. }
  45100. this._collider._radius = this.collisionRadius;
  45101. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45102. this._collisionTriggered = true;
  45103. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45104. }
  45105. else {
  45106. this.position.copyFrom(this._newPosition);
  45107. var up = this.upVector;
  45108. if (this.allowUpsideDown && sinb < 0) {
  45109. up = up.clone();
  45110. up = up.negate();
  45111. }
  45112. if (this.getScene().useRightHandedSystem) {
  45113. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45114. }
  45115. else {
  45116. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45117. }
  45118. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45119. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45120. }
  45121. this._currentTarget = target;
  45122. return this._viewMatrix;
  45123. };
  45124. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45125. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45126. meshes = meshes || this.getScene().meshes;
  45127. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45128. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45129. this.radius = distance * this.zoomOnFactor;
  45130. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45131. };
  45132. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45133. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45134. var meshesOrMinMaxVector;
  45135. var distance;
  45136. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45137. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45138. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45139. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45140. }
  45141. else {
  45142. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45143. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45144. distance = minMaxVectorAndDistance.distance;
  45145. }
  45146. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45147. if (!doNotUpdateMaxZ) {
  45148. this.maxZ = distance * 2;
  45149. }
  45150. };
  45151. /**
  45152. * @override
  45153. * Override Camera.createRigCamera
  45154. */
  45155. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45156. var alphaShift = 0;
  45157. switch (this.cameraRigMode) {
  45158. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45159. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45160. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45161. case BABYLON.Camera.RIG_MODE_VR:
  45162. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45163. break;
  45164. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45165. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45166. break;
  45167. }
  45168. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45169. rigCam._cameraRigParams = {};
  45170. return rigCam;
  45171. };
  45172. /**
  45173. * @override
  45174. * Override Camera._updateRigCameras
  45175. */
  45176. ArcRotateCamera.prototype._updateRigCameras = function () {
  45177. var camLeft = this._rigCameras[0];
  45178. var camRight = this._rigCameras[1];
  45179. camLeft.beta = camRight.beta = this.beta;
  45180. camLeft.radius = camRight.radius = this.radius;
  45181. switch (this.cameraRigMode) {
  45182. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45183. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45184. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45185. case BABYLON.Camera.RIG_MODE_VR:
  45186. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45187. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45188. break;
  45189. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45190. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45191. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45192. break;
  45193. }
  45194. _super.prototype._updateRigCameras.call(this);
  45195. };
  45196. ArcRotateCamera.prototype.dispose = function () {
  45197. this.inputs.clear();
  45198. _super.prototype.dispose.call(this);
  45199. };
  45200. ArcRotateCamera.prototype.getClassName = function () {
  45201. return "ArcRotateCamera";
  45202. };
  45203. __decorate([
  45204. BABYLON.serialize()
  45205. ], ArcRotateCamera.prototype, "alpha", void 0);
  45206. __decorate([
  45207. BABYLON.serialize()
  45208. ], ArcRotateCamera.prototype, "beta", void 0);
  45209. __decorate([
  45210. BABYLON.serialize()
  45211. ], ArcRotateCamera.prototype, "radius", void 0);
  45212. __decorate([
  45213. BABYLON.serializeAsVector3("target")
  45214. ], ArcRotateCamera.prototype, "_target", void 0);
  45215. __decorate([
  45216. BABYLON.serialize()
  45217. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45218. __decorate([
  45219. BABYLON.serialize()
  45220. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45221. __decorate([
  45222. BABYLON.serialize()
  45223. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45224. __decorate([
  45225. BABYLON.serialize()
  45226. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45227. __decorate([
  45228. BABYLON.serialize()
  45229. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45230. __decorate([
  45231. BABYLON.serialize()
  45232. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45233. __decorate([
  45234. BABYLON.serialize()
  45235. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45236. __decorate([
  45237. BABYLON.serialize()
  45238. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45239. __decorate([
  45240. BABYLON.serialize()
  45241. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45242. __decorate([
  45243. BABYLON.serialize()
  45244. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45245. __decorate([
  45246. BABYLON.serialize()
  45247. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45248. __decorate([
  45249. BABYLON.serialize()
  45250. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45251. __decorate([
  45252. BABYLON.serialize()
  45253. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45254. __decorate([
  45255. BABYLON.serializeAsVector3()
  45256. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45257. __decorate([
  45258. BABYLON.serialize()
  45259. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45260. __decorate([
  45261. BABYLON.serialize()
  45262. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45263. __decorate([
  45264. BABYLON.serialize()
  45265. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45266. return ArcRotateCamera;
  45267. }(BABYLON.TargetCamera));
  45268. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45269. })(BABYLON || (BABYLON = {}));
  45270. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45271. var BABYLON;
  45272. (function (BABYLON) {
  45273. /**
  45274. * The HemisphericLight simulates the ambient environment light,
  45275. * so the passed direction is the light reflection direction, not the incoming direction.
  45276. */
  45277. var HemisphericLight = /** @class */ (function (_super) {
  45278. __extends(HemisphericLight, _super);
  45279. /**
  45280. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45281. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45282. * The HemisphericLight can't cast shadows.
  45283. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45284. * @param name The friendly name of the light
  45285. * @param direction The direction of the light reflection
  45286. * @param scene The scene the light belongs to
  45287. */
  45288. function HemisphericLight(name, direction, scene) {
  45289. var _this = _super.call(this, name, scene) || this;
  45290. /**
  45291. * The groundColor is the light in the opposite direction to the one specified during creation.
  45292. * 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.
  45293. */
  45294. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45295. _this.direction = direction || BABYLON.Vector3.Up();
  45296. return _this;
  45297. }
  45298. HemisphericLight.prototype._buildUniformLayout = function () {
  45299. this._uniformBuffer.addUniform("vLightData", 4);
  45300. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45301. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45302. this._uniformBuffer.addUniform("vLightGround", 3);
  45303. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45304. this._uniformBuffer.addUniform("depthValues", 2);
  45305. this._uniformBuffer.create();
  45306. };
  45307. /**
  45308. * Returns the string "HemisphericLight".
  45309. * @return The class name
  45310. */
  45311. HemisphericLight.prototype.getClassName = function () {
  45312. return "HemisphericLight";
  45313. };
  45314. /**
  45315. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45316. * Returns the updated direction.
  45317. * @param target The target the direction should point to
  45318. * @return The computed direction
  45319. */
  45320. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45321. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45322. return this.direction;
  45323. };
  45324. /**
  45325. * Returns the shadow generator associated to the light.
  45326. * @returns Always null for hemispheric lights because it does not support shadows.
  45327. */
  45328. HemisphericLight.prototype.getShadowGenerator = function () {
  45329. return null;
  45330. };
  45331. /**
  45332. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45333. * @param effect The effect to update
  45334. * @param lightIndex The index of the light in the effect to update
  45335. * @returns The hemispheric light
  45336. */
  45337. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45338. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45339. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45340. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45341. return this;
  45342. };
  45343. /**
  45344. * @ignore internal use only.
  45345. */
  45346. HemisphericLight.prototype._getWorldMatrix = function () {
  45347. if (!this._worldMatrix) {
  45348. this._worldMatrix = BABYLON.Matrix.Identity();
  45349. }
  45350. return this._worldMatrix;
  45351. };
  45352. /**
  45353. * Returns the integer 3.
  45354. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45355. */
  45356. HemisphericLight.prototype.getTypeID = function () {
  45357. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45358. };
  45359. __decorate([
  45360. BABYLON.serializeAsColor3()
  45361. ], HemisphericLight.prototype, "groundColor", void 0);
  45362. __decorate([
  45363. BABYLON.serializeAsVector3()
  45364. ], HemisphericLight.prototype, "direction", void 0);
  45365. return HemisphericLight;
  45366. }(BABYLON.Light));
  45367. BABYLON.HemisphericLight = HemisphericLight;
  45368. })(BABYLON || (BABYLON = {}));
  45369. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45370. var BABYLON;
  45371. (function (BABYLON) {
  45372. /**
  45373. * Base implementation of @see IShadowLight
  45374. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45375. */
  45376. var ShadowLight = /** @class */ (function (_super) {
  45377. __extends(ShadowLight, _super);
  45378. function ShadowLight() {
  45379. var _this = _super !== null && _super.apply(this, arguments) || this;
  45380. _this._needProjectionMatrixCompute = true;
  45381. return _this;
  45382. }
  45383. ShadowLight.prototype._setPosition = function (value) {
  45384. this._position = value;
  45385. };
  45386. Object.defineProperty(ShadowLight.prototype, "position", {
  45387. /**
  45388. * Sets the position the shadow will be casted from. Also use as the light position for both
  45389. * point and spot lights.
  45390. */
  45391. get: function () {
  45392. return this._position;
  45393. },
  45394. /**
  45395. * Sets the position the shadow will be casted from. Also use as the light position for both
  45396. * point and spot lights.
  45397. */
  45398. set: function (value) {
  45399. this._setPosition(value);
  45400. },
  45401. enumerable: true,
  45402. configurable: true
  45403. });
  45404. ShadowLight.prototype._setDirection = function (value) {
  45405. this._direction = value;
  45406. };
  45407. Object.defineProperty(ShadowLight.prototype, "direction", {
  45408. /**
  45409. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45410. * Also use as the light direction on spot and directional lights.
  45411. */
  45412. get: function () {
  45413. return this._direction;
  45414. },
  45415. /**
  45416. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45417. * Also use as the light direction on spot and directional lights.
  45418. */
  45419. set: function (value) {
  45420. this._setDirection(value);
  45421. },
  45422. enumerable: true,
  45423. configurable: true
  45424. });
  45425. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45426. /**
  45427. * Gets the shadow projection clipping minimum z value.
  45428. */
  45429. get: function () {
  45430. return this._shadowMinZ;
  45431. },
  45432. /**
  45433. * Sets the shadow projection clipping minimum z value.
  45434. */
  45435. set: function (value) {
  45436. this._shadowMinZ = value;
  45437. this.forceProjectionMatrixCompute();
  45438. },
  45439. enumerable: true,
  45440. configurable: true
  45441. });
  45442. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45443. /**
  45444. * Sets the shadow projection clipping maximum z value.
  45445. */
  45446. get: function () {
  45447. return this._shadowMaxZ;
  45448. },
  45449. /**
  45450. * Gets the shadow projection clipping maximum z value.
  45451. */
  45452. set: function (value) {
  45453. this._shadowMaxZ = value;
  45454. this.forceProjectionMatrixCompute();
  45455. },
  45456. enumerable: true,
  45457. configurable: true
  45458. });
  45459. /**
  45460. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45461. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45462. */
  45463. ShadowLight.prototype.computeTransformedInformation = function () {
  45464. if (this.parent && this.parent.getWorldMatrix) {
  45465. if (!this.transformedPosition) {
  45466. this.transformedPosition = BABYLON.Vector3.Zero();
  45467. }
  45468. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45469. // In case the direction is present.
  45470. if (this.direction) {
  45471. if (!this.transformedDirection) {
  45472. this.transformedDirection = BABYLON.Vector3.Zero();
  45473. }
  45474. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45475. }
  45476. return true;
  45477. }
  45478. return false;
  45479. };
  45480. /**
  45481. * Return the depth scale used for the shadow map.
  45482. * @returns the depth scale.
  45483. */
  45484. ShadowLight.prototype.getDepthScale = function () {
  45485. return 50.0;
  45486. };
  45487. /**
  45488. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45489. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45490. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45491. */
  45492. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45493. return this.transformedDirection ? this.transformedDirection : this.direction;
  45494. };
  45495. /**
  45496. * Returns the ShadowLight absolute position in the World.
  45497. * @returns the position vector in world space
  45498. */
  45499. ShadowLight.prototype.getAbsolutePosition = function () {
  45500. return this.transformedPosition ? this.transformedPosition : this.position;
  45501. };
  45502. /**
  45503. * Sets the ShadowLight direction toward the passed target.
  45504. * @param target The point tot target in local space
  45505. * @returns the updated ShadowLight direction
  45506. */
  45507. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45508. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45509. return this.direction;
  45510. };
  45511. /**
  45512. * Returns the light rotation in euler definition.
  45513. * @returns the x y z rotation in local space.
  45514. */
  45515. ShadowLight.prototype.getRotation = function () {
  45516. this.direction.normalize();
  45517. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45518. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45519. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45520. };
  45521. /**
  45522. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45523. * @returns true if a cube texture needs to be use
  45524. */
  45525. ShadowLight.prototype.needCube = function () {
  45526. return false;
  45527. };
  45528. /**
  45529. * Detects if the projection matrix requires to be recomputed this frame.
  45530. * @returns true if it requires to be recomputed otherwise, false.
  45531. */
  45532. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45533. return this._needProjectionMatrixCompute;
  45534. };
  45535. /**
  45536. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45537. */
  45538. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45539. this._needProjectionMatrixCompute = true;
  45540. };
  45541. /**
  45542. * Get the world matrix of the sahdow lights.
  45543. * @ignore Internal Use Only
  45544. */
  45545. ShadowLight.prototype._getWorldMatrix = function () {
  45546. if (!this._worldMatrix) {
  45547. this._worldMatrix = BABYLON.Matrix.Identity();
  45548. }
  45549. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45550. return this._worldMatrix;
  45551. };
  45552. /**
  45553. * Gets the minZ used for shadow according to both the scene and the light.
  45554. * @param activeCamera The camera we are returning the min for
  45555. * @returns the depth min z
  45556. */
  45557. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45558. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45559. };
  45560. /**
  45561. * Gets the maxZ used for shadow according to both the scene and the light.
  45562. * @param activeCamera The camera we are returning the max for
  45563. * @returns the depth max z
  45564. */
  45565. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45566. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45567. };
  45568. /**
  45569. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45570. * @param matrix The materix to updated with the projection information
  45571. * @param viewMatrix The transform matrix of the light
  45572. * @param renderList The list of mesh to render in the map
  45573. * @returns The current light
  45574. */
  45575. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45576. if (this.customProjectionMatrixBuilder) {
  45577. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45578. }
  45579. else {
  45580. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45581. }
  45582. return this;
  45583. };
  45584. __decorate([
  45585. BABYLON.serializeAsVector3()
  45586. ], ShadowLight.prototype, "position", null);
  45587. __decorate([
  45588. BABYLON.serializeAsVector3()
  45589. ], ShadowLight.prototype, "direction", null);
  45590. __decorate([
  45591. BABYLON.serialize()
  45592. ], ShadowLight.prototype, "shadowMinZ", null);
  45593. __decorate([
  45594. BABYLON.serialize()
  45595. ], ShadowLight.prototype, "shadowMaxZ", null);
  45596. return ShadowLight;
  45597. }(BABYLON.Light));
  45598. BABYLON.ShadowLight = ShadowLight;
  45599. })(BABYLON || (BABYLON = {}));
  45600. //# sourceMappingURL=babylon.shadowLight.js.map
  45601. var BABYLON;
  45602. (function (BABYLON) {
  45603. /**
  45604. * A point light is a light defined by an unique point in world space.
  45605. * The light is emitted in every direction from this point.
  45606. * A good example of a point light is a standard light bulb.
  45607. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45608. */
  45609. var PointLight = /** @class */ (function (_super) {
  45610. __extends(PointLight, _super);
  45611. /**
  45612. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45613. * A PointLight emits the light in every direction.
  45614. * It can cast shadows.
  45615. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45616. * ```javascript
  45617. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45618. * ```
  45619. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45620. * @param name The light friendly name
  45621. * @param position The position of the point light in the scene
  45622. * @param scene The scene the lights belongs to
  45623. */
  45624. function PointLight(name, position, scene) {
  45625. var _this = _super.call(this, name, scene) || this;
  45626. _this._shadowAngle = Math.PI / 2;
  45627. _this.position = position;
  45628. return _this;
  45629. }
  45630. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45631. /**
  45632. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45633. * This specifies what angle the shadow will use to be created.
  45634. *
  45635. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45636. */
  45637. get: function () {
  45638. return this._shadowAngle;
  45639. },
  45640. /**
  45641. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45642. * This specifies what angle the shadow will use to be created.
  45643. *
  45644. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45645. */
  45646. set: function (value) {
  45647. this._shadowAngle = value;
  45648. this.forceProjectionMatrixCompute();
  45649. },
  45650. enumerable: true,
  45651. configurable: true
  45652. });
  45653. Object.defineProperty(PointLight.prototype, "direction", {
  45654. /**
  45655. * Gets the direction if it has been set.
  45656. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45657. */
  45658. get: function () {
  45659. return this._direction;
  45660. },
  45661. /**
  45662. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45663. */
  45664. set: function (value) {
  45665. var previousNeedCube = this.needCube();
  45666. this._direction = value;
  45667. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45668. this._shadowGenerator.recreateShadowMap();
  45669. }
  45670. },
  45671. enumerable: true,
  45672. configurable: true
  45673. });
  45674. /**
  45675. * Returns the string "PointLight"
  45676. * @returns the class name
  45677. */
  45678. PointLight.prototype.getClassName = function () {
  45679. return "PointLight";
  45680. };
  45681. /**
  45682. * Returns the integer 0.
  45683. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45684. */
  45685. PointLight.prototype.getTypeID = function () {
  45686. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45687. };
  45688. /**
  45689. * Specifies wether or not the shadowmap should be a cube texture.
  45690. * @returns true if the shadowmap needs to be a cube texture.
  45691. */
  45692. PointLight.prototype.needCube = function () {
  45693. return !this.direction;
  45694. };
  45695. /**
  45696. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45697. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45698. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45699. */
  45700. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45701. if (this.direction) {
  45702. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45703. }
  45704. else {
  45705. switch (faceIndex) {
  45706. case 0:
  45707. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45708. case 1:
  45709. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45710. case 2:
  45711. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45712. case 3:
  45713. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45714. case 4:
  45715. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45716. case 5:
  45717. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45718. }
  45719. }
  45720. return BABYLON.Vector3.Zero();
  45721. };
  45722. /**
  45723. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45724. * - fov = PI / 2
  45725. * - aspect ratio : 1.0
  45726. * - z-near and far equal to the active camera minZ and maxZ.
  45727. * Returns the PointLight.
  45728. */
  45729. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45730. var activeCamera = this.getScene().activeCamera;
  45731. if (!activeCamera) {
  45732. return;
  45733. }
  45734. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45735. };
  45736. PointLight.prototype._buildUniformLayout = function () {
  45737. this._uniformBuffer.addUniform("vLightData", 4);
  45738. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45739. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45740. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45741. this._uniformBuffer.addUniform("depthValues", 2);
  45742. this._uniformBuffer.create();
  45743. };
  45744. /**
  45745. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45746. * @param effect The effect to update
  45747. * @param lightIndex The index of the light in the effect to update
  45748. * @returns The point light
  45749. */
  45750. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45751. if (this.computeTransformedInformation()) {
  45752. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45753. return this;
  45754. }
  45755. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45756. return this;
  45757. };
  45758. __decorate([
  45759. BABYLON.serialize()
  45760. ], PointLight.prototype, "shadowAngle", null);
  45761. return PointLight;
  45762. }(BABYLON.ShadowLight));
  45763. BABYLON.PointLight = PointLight;
  45764. })(BABYLON || (BABYLON = {}));
  45765. //# sourceMappingURL=babylon.pointLight.js.map
  45766. var BABYLON;
  45767. (function (BABYLON) {
  45768. /**
  45769. * A directional light is defined by a direction (what a surprise!).
  45770. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45771. * 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.
  45772. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45773. */
  45774. var DirectionalLight = /** @class */ (function (_super) {
  45775. __extends(DirectionalLight, _super);
  45776. /**
  45777. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45778. * The directional light is emitted from everywhere in the given direction.
  45779. * It can cast shawdows.
  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
  45783. * @param scene The scene the light belongs to
  45784. */
  45785. function DirectionalLight(name, direction, scene) {
  45786. var _this = _super.call(this, name, scene) || this;
  45787. _this._shadowFrustumSize = 0;
  45788. _this._shadowOrthoScale = 0.5;
  45789. /**
  45790. * Automatically compute the projection matrix to best fit (including all the casters)
  45791. * on each frame.
  45792. */
  45793. _this.autoUpdateExtends = true;
  45794. // Cache
  45795. _this._orthoLeft = Number.MAX_VALUE;
  45796. _this._orthoRight = Number.MIN_VALUE;
  45797. _this._orthoTop = Number.MIN_VALUE;
  45798. _this._orthoBottom = Number.MAX_VALUE;
  45799. _this.position = direction.scale(-1.0);
  45800. _this.direction = direction;
  45801. return _this;
  45802. }
  45803. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45804. /**
  45805. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45806. */
  45807. get: function () {
  45808. return this._shadowFrustumSize;
  45809. },
  45810. /**
  45811. * Specifies a fix frustum size for the shadow generation.
  45812. */
  45813. set: function (value) {
  45814. this._shadowFrustumSize = value;
  45815. this.forceProjectionMatrixCompute();
  45816. },
  45817. enumerable: true,
  45818. configurable: true
  45819. });
  45820. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45821. /**
  45822. * Gets the shadow projection scale against the optimal computed one.
  45823. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45824. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45825. */
  45826. get: function () {
  45827. return this._shadowOrthoScale;
  45828. },
  45829. /**
  45830. * Sets the shadow projection scale against the optimal computed one.
  45831. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45832. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45833. */
  45834. set: function (value) {
  45835. this._shadowOrthoScale = value;
  45836. this.forceProjectionMatrixCompute();
  45837. },
  45838. enumerable: true,
  45839. configurable: true
  45840. });
  45841. /**
  45842. * Returns the string "DirectionalLight".
  45843. * @return The class name
  45844. */
  45845. DirectionalLight.prototype.getClassName = function () {
  45846. return "DirectionalLight";
  45847. };
  45848. /**
  45849. * Returns the integer 1.
  45850. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45851. */
  45852. DirectionalLight.prototype.getTypeID = function () {
  45853. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45854. };
  45855. /**
  45856. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45857. * Returns the DirectionalLight Shadow projection matrix.
  45858. */
  45859. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45860. if (this.shadowFrustumSize > 0) {
  45861. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45862. }
  45863. else {
  45864. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45865. }
  45866. };
  45867. /**
  45868. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45869. * Returns the DirectionalLight Shadow projection matrix.
  45870. */
  45871. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45872. var activeCamera = this.getScene().activeCamera;
  45873. if (!activeCamera) {
  45874. return;
  45875. }
  45876. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45877. };
  45878. /**
  45879. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45880. * Returns the DirectionalLight Shadow projection matrix.
  45881. */
  45882. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45883. var activeCamera = this.getScene().activeCamera;
  45884. if (!activeCamera) {
  45885. return;
  45886. }
  45887. // Check extends
  45888. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45889. var tempVector3 = BABYLON.Vector3.Zero();
  45890. this._orthoLeft = Number.MAX_VALUE;
  45891. this._orthoRight = Number.MIN_VALUE;
  45892. this._orthoTop = Number.MIN_VALUE;
  45893. this._orthoBottom = Number.MAX_VALUE;
  45894. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45895. var mesh = renderList[meshIndex];
  45896. if (!mesh) {
  45897. continue;
  45898. }
  45899. var boundingInfo = mesh.getBoundingInfo();
  45900. var boundingBox = boundingInfo.boundingBox;
  45901. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45902. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45903. if (tempVector3.x < this._orthoLeft)
  45904. this._orthoLeft = tempVector3.x;
  45905. if (tempVector3.y < this._orthoBottom)
  45906. this._orthoBottom = tempVector3.y;
  45907. if (tempVector3.x > this._orthoRight)
  45908. this._orthoRight = tempVector3.x;
  45909. if (tempVector3.y > this._orthoTop)
  45910. this._orthoTop = tempVector3.y;
  45911. }
  45912. }
  45913. }
  45914. var xOffset = this._orthoRight - this._orthoLeft;
  45915. var yOffset = this._orthoTop - this._orthoBottom;
  45916. 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);
  45917. };
  45918. DirectionalLight.prototype._buildUniformLayout = function () {
  45919. this._uniformBuffer.addUniform("vLightData", 4);
  45920. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45921. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45922. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45923. this._uniformBuffer.addUniform("depthValues", 2);
  45924. this._uniformBuffer.create();
  45925. };
  45926. /**
  45927. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45928. * @param effect The effect to update
  45929. * @param lightIndex The index of the light in the effect to update
  45930. * @returns The directional light
  45931. */
  45932. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45933. if (this.computeTransformedInformation()) {
  45934. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45935. return this;
  45936. }
  45937. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45938. return this;
  45939. };
  45940. /**
  45941. * Gets the minZ used for shadow according to both the scene and the light.
  45942. *
  45943. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45944. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45945. * @param activeCamera The camera we are returning the min for
  45946. * @returns the depth min z
  45947. */
  45948. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45949. return 1;
  45950. };
  45951. /**
  45952. * Gets the maxZ used for shadow according to both the scene and the light.
  45953. *
  45954. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45955. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45956. * @param activeCamera The camera we are returning the max for
  45957. * @returns the depth max z
  45958. */
  45959. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45960. return 1;
  45961. };
  45962. __decorate([
  45963. BABYLON.serialize()
  45964. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45965. __decorate([
  45966. BABYLON.serialize()
  45967. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45968. __decorate([
  45969. BABYLON.serialize()
  45970. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45971. return DirectionalLight;
  45972. }(BABYLON.ShadowLight));
  45973. BABYLON.DirectionalLight = DirectionalLight;
  45974. })(BABYLON || (BABYLON = {}));
  45975. //# sourceMappingURL=babylon.directionalLight.js.map
  45976. var BABYLON;
  45977. (function (BABYLON) {
  45978. /**
  45979. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45980. * These values define a cone of light starting from the position, emitting toward the direction.
  45981. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45982. * and the exponent defines the speed of the decay of the light with distance (reach).
  45983. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45984. */
  45985. var SpotLight = /** @class */ (function (_super) {
  45986. __extends(SpotLight, _super);
  45987. /**
  45988. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45989. * It can cast shadows.
  45990. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45991. * @param name The light friendly name
  45992. * @param position The position of the spot light in the scene
  45993. * @param direction The direction of the light in the scene
  45994. * @param angle The cone angle of the light in Radians
  45995. * @param exponent The light decay speed with the distance from the emission spot
  45996. * @param scene The scene the lights belongs to
  45997. */
  45998. function SpotLight(name, position, direction, angle, exponent, scene) {
  45999. var _this = _super.call(this, name, scene) || this;
  46000. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46001. _this._projectionTextureLightNear = 1e-6;
  46002. _this._projectionTextureLightFar = 1000.0;
  46003. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46004. _this._projectionTextureViewLightDirty = true;
  46005. _this._projectionTextureProjectionLightDirty = true;
  46006. _this._projectionTextureDirty = true;
  46007. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46008. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46009. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46010. _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);
  46011. _this.position = position;
  46012. _this.direction = direction;
  46013. _this.angle = angle;
  46014. _this.exponent = exponent;
  46015. return _this;
  46016. }
  46017. Object.defineProperty(SpotLight.prototype, "angle", {
  46018. /**
  46019. * Gets the cone angle of the spot light in Radians.
  46020. */
  46021. get: function () {
  46022. return this._angle;
  46023. },
  46024. /**
  46025. * Sets the cone angle of the spot light in Radians.
  46026. */
  46027. set: function (value) {
  46028. this._angle = value;
  46029. this._projectionTextureProjectionLightDirty = true;
  46030. this.forceProjectionMatrixCompute();
  46031. },
  46032. enumerable: true,
  46033. configurable: true
  46034. });
  46035. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46036. /**
  46037. * Allows scaling the angle of the light for shadow generation only.
  46038. */
  46039. get: function () {
  46040. return this._shadowAngleScale;
  46041. },
  46042. /**
  46043. * Allows scaling the angle of the light for shadow generation only.
  46044. */
  46045. set: function (value) {
  46046. this._shadowAngleScale = value;
  46047. this.forceProjectionMatrixCompute();
  46048. },
  46049. enumerable: true,
  46050. configurable: true
  46051. });
  46052. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46053. /**
  46054. * Allows reading the projecton texture
  46055. */
  46056. get: function () {
  46057. return this._projectionTextureMatrix;
  46058. },
  46059. enumerable: true,
  46060. configurable: true
  46061. });
  46062. ;
  46063. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46064. /**
  46065. * Gets the near clip of the Spotlight for texture projection.
  46066. */
  46067. get: function () {
  46068. return this._projectionTextureLightNear;
  46069. },
  46070. /**
  46071. * Sets the near clip of the Spotlight for texture projection.
  46072. */
  46073. set: function (value) {
  46074. this._projectionTextureLightNear = value;
  46075. this._projectionTextureProjectionLightDirty = true;
  46076. },
  46077. enumerable: true,
  46078. configurable: true
  46079. });
  46080. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46081. /**
  46082. * Gets the far clip of the Spotlight for texture projection.
  46083. */
  46084. get: function () {
  46085. return this._projectionTextureLightFar;
  46086. },
  46087. /**
  46088. * Sets the far clip of the Spotlight for texture projection.
  46089. */
  46090. set: function (value) {
  46091. this._projectionTextureLightFar = value;
  46092. this._projectionTextureProjectionLightDirty = true;
  46093. },
  46094. enumerable: true,
  46095. configurable: true
  46096. });
  46097. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46098. /**
  46099. * Gets the Up vector of the Spotlight for texture projection.
  46100. */
  46101. get: function () {
  46102. return this._projectionTextureUpDirection;
  46103. },
  46104. /**
  46105. * Sets the Up vector of the Spotlight for texture projection.
  46106. */
  46107. set: function (value) {
  46108. this._projectionTextureUpDirection = value;
  46109. this._projectionTextureProjectionLightDirty = true;
  46110. },
  46111. enumerable: true,
  46112. configurable: true
  46113. });
  46114. ;
  46115. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46116. /**
  46117. * Gets the projection texture of the light.
  46118. */
  46119. get: function () {
  46120. return this._projectionTexture;
  46121. },
  46122. /**
  46123. * Sets the projection texture of the light.
  46124. */
  46125. set: function (value) {
  46126. this._projectionTexture = value;
  46127. this._projectionTextureDirty = true;
  46128. },
  46129. enumerable: true,
  46130. configurable: true
  46131. });
  46132. /**
  46133. * Returns the string "SpotLight".
  46134. * @returns the class name
  46135. */
  46136. SpotLight.prototype.getClassName = function () {
  46137. return "SpotLight";
  46138. };
  46139. /**
  46140. * Returns the integer 2.
  46141. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46142. */
  46143. SpotLight.prototype.getTypeID = function () {
  46144. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46145. };
  46146. /**
  46147. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46148. */
  46149. SpotLight.prototype._setDirection = function (value) {
  46150. _super.prototype._setDirection.call(this, value);
  46151. this._projectionTextureViewLightDirty = true;
  46152. };
  46153. /**
  46154. * Overrides the position setter to recompute the projection texture view light Matrix.
  46155. */
  46156. SpotLight.prototype._setPosition = function (value) {
  46157. _super.prototype._setPosition.call(this, value);
  46158. this._projectionTextureViewLightDirty = true;
  46159. };
  46160. /**
  46161. * 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.
  46162. * Returns the SpotLight.
  46163. */
  46164. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46165. var activeCamera = this.getScene().activeCamera;
  46166. if (!activeCamera) {
  46167. return;
  46168. }
  46169. this._shadowAngleScale = this._shadowAngleScale || 1;
  46170. var angle = this._shadowAngleScale * this._angle;
  46171. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46172. };
  46173. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46174. this._projectionTextureViewLightDirty = false;
  46175. this._projectionTextureDirty = true;
  46176. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46177. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46178. };
  46179. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46180. this._projectionTextureProjectionLightDirty = false;
  46181. this._projectionTextureDirty = true;
  46182. var light_far = this.projectionTextureLightFar;
  46183. var light_near = this.projectionTextureLightNear;
  46184. var P = light_far / (light_far - light_near);
  46185. var Q = -P * light_near;
  46186. var S = 1.0 / Math.tan(this._angle / 2.0);
  46187. var A = 1.0;
  46188. 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);
  46189. };
  46190. /**
  46191. * Main function for light texture projection matrix computing.
  46192. */
  46193. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46194. this._projectionTextureDirty = false;
  46195. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46196. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46197. };
  46198. SpotLight.prototype._buildUniformLayout = function () {
  46199. this._uniformBuffer.addUniform("vLightData", 4);
  46200. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46201. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46202. this._uniformBuffer.addUniform("vLightDirection", 3);
  46203. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46204. this._uniformBuffer.addUniform("depthValues", 2);
  46205. this._uniformBuffer.create();
  46206. };
  46207. /**
  46208. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46209. * @param effect The effect to update
  46210. * @param lightIndex The index of the light in the effect to update
  46211. * @returns The spot light
  46212. */
  46213. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46214. var normalizeDirection;
  46215. if (this.computeTransformedInformation()) {
  46216. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46217. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46218. }
  46219. else {
  46220. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46221. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46222. }
  46223. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46224. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46225. if (this._projectionTextureViewLightDirty) {
  46226. this._computeProjectionTextureViewLightMatrix();
  46227. }
  46228. if (this._projectionTextureProjectionLightDirty) {
  46229. this._computeProjectionTextureProjectionLightMatrix();
  46230. }
  46231. if (this._projectionTextureDirty) {
  46232. this._computeProjectionTextureMatrix();
  46233. }
  46234. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46235. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46236. }
  46237. return this;
  46238. };
  46239. /**
  46240. * Disposes the light and the associated resources.
  46241. */
  46242. SpotLight.prototype.dispose = function () {
  46243. _super.prototype.dispose.call(this);
  46244. if (this._projectionTexture) {
  46245. this._projectionTexture.dispose();
  46246. }
  46247. };
  46248. __decorate([
  46249. BABYLON.serialize()
  46250. ], SpotLight.prototype, "angle", null);
  46251. __decorate([
  46252. BABYLON.serialize()
  46253. ], SpotLight.prototype, "shadowAngleScale", null);
  46254. __decorate([
  46255. BABYLON.serialize()
  46256. ], SpotLight.prototype, "exponent", void 0);
  46257. __decorate([
  46258. BABYLON.serialize()
  46259. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46260. __decorate([
  46261. BABYLON.serialize()
  46262. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46263. __decorate([
  46264. BABYLON.serialize()
  46265. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46266. __decorate([
  46267. BABYLON.serializeAsTexture("projectedLightTexture")
  46268. ], SpotLight.prototype, "_projectionTexture", void 0);
  46269. return SpotLight;
  46270. }(BABYLON.ShadowLight));
  46271. BABYLON.SpotLight = SpotLight;
  46272. })(BABYLON || (BABYLON = {}));
  46273. //# sourceMappingURL=babylon.spotLight.js.map
  46274. var BABYLON;
  46275. (function (BABYLON) {
  46276. /**
  46277. * Class used to override all child animations of a given target
  46278. */
  46279. var AnimationPropertiesOverride = /** @class */ (function () {
  46280. function AnimationPropertiesOverride() {
  46281. /**
  46282. * Gets or sets a value indicating if animation blending must be used
  46283. */
  46284. this.enableBlending = false;
  46285. /**
  46286. * Gets or sets the blending speed to use when enableBlending is true
  46287. */
  46288. this.blendingSpeed = 0.01;
  46289. /**
  46290. * Gets or sets the default loop mode to use
  46291. */
  46292. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46293. }
  46294. return AnimationPropertiesOverride;
  46295. }());
  46296. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46297. })(BABYLON || (BABYLON = {}));
  46298. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46299. var BABYLON;
  46300. (function (BABYLON) {
  46301. var AnimationRange = /** @class */ (function () {
  46302. function AnimationRange(name, from, to) {
  46303. this.name = name;
  46304. this.from = from;
  46305. this.to = to;
  46306. }
  46307. AnimationRange.prototype.clone = function () {
  46308. return new AnimationRange(this.name, this.from, this.to);
  46309. };
  46310. return AnimationRange;
  46311. }());
  46312. BABYLON.AnimationRange = AnimationRange;
  46313. /**
  46314. * Composed of a frame, and an action function
  46315. */
  46316. var AnimationEvent = /** @class */ (function () {
  46317. function AnimationEvent(frame, action, onlyOnce) {
  46318. this.frame = frame;
  46319. this.action = action;
  46320. this.onlyOnce = onlyOnce;
  46321. this.isDone = false;
  46322. }
  46323. return AnimationEvent;
  46324. }());
  46325. BABYLON.AnimationEvent = AnimationEvent;
  46326. var PathCursor = /** @class */ (function () {
  46327. function PathCursor(path) {
  46328. this.path = path;
  46329. this._onchange = new Array();
  46330. this.value = 0;
  46331. this.animations = new Array();
  46332. }
  46333. PathCursor.prototype.getPoint = function () {
  46334. var point = this.path.getPointAtLengthPosition(this.value);
  46335. return new BABYLON.Vector3(point.x, 0, point.y);
  46336. };
  46337. PathCursor.prototype.moveAhead = function (step) {
  46338. if (step === void 0) { step = 0.002; }
  46339. this.move(step);
  46340. return this;
  46341. };
  46342. PathCursor.prototype.moveBack = function (step) {
  46343. if (step === void 0) { step = 0.002; }
  46344. this.move(-step);
  46345. return this;
  46346. };
  46347. PathCursor.prototype.move = function (step) {
  46348. if (Math.abs(step) > 1) {
  46349. throw "step size should be less than 1.";
  46350. }
  46351. this.value += step;
  46352. this.ensureLimits();
  46353. this.raiseOnChange();
  46354. return this;
  46355. };
  46356. PathCursor.prototype.ensureLimits = function () {
  46357. while (this.value > 1) {
  46358. this.value -= 1;
  46359. }
  46360. while (this.value < 0) {
  46361. this.value += 1;
  46362. }
  46363. return this;
  46364. };
  46365. // used by animation engine
  46366. PathCursor.prototype.raiseOnChange = function () {
  46367. var _this = this;
  46368. this._onchange.forEach(function (f) { return f(_this); });
  46369. return this;
  46370. };
  46371. PathCursor.prototype.onchange = function (f) {
  46372. this._onchange.push(f);
  46373. return this;
  46374. };
  46375. return PathCursor;
  46376. }());
  46377. BABYLON.PathCursor = PathCursor;
  46378. var AnimationKeyInterpolation;
  46379. (function (AnimationKeyInterpolation) {
  46380. /**
  46381. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46382. */
  46383. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46384. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46385. var Animation = /** @class */ (function () {
  46386. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46387. this.name = name;
  46388. this.targetProperty = targetProperty;
  46389. this.framePerSecond = framePerSecond;
  46390. this.dataType = dataType;
  46391. this.loopMode = loopMode;
  46392. this.enableBlending = enableBlending;
  46393. this._runtimeAnimations = new Array();
  46394. // The set of event that will be linked to this animation
  46395. this._events = new Array();
  46396. this.blendingSpeed = 0.01;
  46397. this._ranges = {};
  46398. this.targetPropertyPath = targetProperty.split(".");
  46399. this.dataType = dataType;
  46400. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46401. }
  46402. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46403. var dataType = undefined;
  46404. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46405. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46406. }
  46407. else if (from instanceof BABYLON.Quaternion) {
  46408. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46409. }
  46410. else if (from instanceof BABYLON.Vector3) {
  46411. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46412. }
  46413. else if (from instanceof BABYLON.Vector2) {
  46414. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46415. }
  46416. else if (from instanceof BABYLON.Color3) {
  46417. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46418. }
  46419. else if (from instanceof BABYLON.Size) {
  46420. dataType = Animation.ANIMATIONTYPE_SIZE;
  46421. }
  46422. if (dataType == undefined) {
  46423. return null;
  46424. }
  46425. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46426. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46427. animation.setKeys(keys);
  46428. if (easingFunction !== undefined) {
  46429. animation.setEasingFunction(easingFunction);
  46430. }
  46431. return animation;
  46432. };
  46433. /**
  46434. * Sets up an animation.
  46435. * @param property the property to animate
  46436. * @param animationType the animation type to apply
  46437. * @param easingFunction the easing function used in the animation
  46438. * @returns The created animation
  46439. */
  46440. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46441. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46442. animation.setEasingFunction(easingFunction);
  46443. return animation;
  46444. };
  46445. /**
  46446. * Create and start an animation on a node
  46447. * @param {string} name defines the name of the global animation that will be run on all nodes
  46448. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46449. * @param {string} targetProperty defines property to animate
  46450. * @param {number} framePerSecond defines the number of frame per second yo use
  46451. * @param {number} totalFrame defines the number of frames in total
  46452. * @param {any} from defines the initial value
  46453. * @param {any} to defines the final value
  46454. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46455. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46456. * @param onAnimationEnd defines the callback to call when animation end
  46457. * @returns the animatable created for this animation
  46458. */
  46459. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46460. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46461. if (!animation) {
  46462. return null;
  46463. }
  46464. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46465. };
  46466. /**
  46467. * Create and start an animation on a node and its descendants
  46468. * @param {string} name defines the name of the global animation that will be run on all nodes
  46469. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46470. * @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.
  46471. * @param {string} targetProperty defines property to animate
  46472. * @param {number} framePerSecond defines the number of frame per second yo use
  46473. * @param {number} totalFrame defines the number of frames in total
  46474. * @param {any} from defines the initial value
  46475. * @param {any} to defines the final value
  46476. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46477. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46478. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46479. * @returns the list of animatables created for all nodes
  46480. * @example https://www.babylonjs-playground.com/#MH0VLI
  46481. */
  46482. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46483. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46484. if (!animation) {
  46485. return null;
  46486. }
  46487. var scene = node.getScene();
  46488. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46489. };
  46490. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46491. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46492. if (!animation) {
  46493. return null;
  46494. }
  46495. node.animations.push(animation);
  46496. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46497. };
  46498. /**
  46499. * Transition property of the Camera to the target Value.
  46500. * @param property The property to transition
  46501. * @param targetValue The target Value of the property
  46502. * @param host The object where the property to animate belongs
  46503. * @param scene Scene used to run the animation
  46504. * @param frameRate Framerate (in frame/s) to use
  46505. * @param transition The transition type we want to use
  46506. * @param duration The duration of the animation, in milliseconds
  46507. * @param onAnimationEnd Call back trigger at the end of the animation.
  46508. */
  46509. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46510. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46511. if (duration <= 0) {
  46512. host[property] = targetValue;
  46513. if (onAnimationEnd) {
  46514. onAnimationEnd();
  46515. }
  46516. return null;
  46517. }
  46518. var endFrame = frameRate * (duration / 1000);
  46519. transition.setKeys([{
  46520. frame: 0,
  46521. value: host[property].clone ? host[property].clone() : host[property]
  46522. },
  46523. {
  46524. frame: endFrame,
  46525. value: targetValue
  46526. }]);
  46527. if (!host.animations) {
  46528. host.animations = [];
  46529. }
  46530. host.animations.push(transition);
  46531. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46532. animation.onAnimationEnd = onAnimationEnd;
  46533. return animation;
  46534. };
  46535. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46536. /**
  46537. * Return the array of runtime animations currently using this animation
  46538. */
  46539. get: function () {
  46540. return this._runtimeAnimations;
  46541. },
  46542. enumerable: true,
  46543. configurable: true
  46544. });
  46545. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46546. get: function () {
  46547. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46548. var runtimeAnimation = _a[_i];
  46549. if (!runtimeAnimation.isStopped) {
  46550. return true;
  46551. }
  46552. }
  46553. return false;
  46554. },
  46555. enumerable: true,
  46556. configurable: true
  46557. });
  46558. // Methods
  46559. /**
  46560. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46561. */
  46562. Animation.prototype.toString = function (fullDetails) {
  46563. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46564. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46565. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46566. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46567. if (fullDetails) {
  46568. ret += ", Ranges: {";
  46569. var first = true;
  46570. for (var name in this._ranges) {
  46571. if (first) {
  46572. ret += ", ";
  46573. first = false;
  46574. }
  46575. ret += name;
  46576. }
  46577. ret += "}";
  46578. }
  46579. return ret;
  46580. };
  46581. /**
  46582. * Add an event to this animation.
  46583. */
  46584. Animation.prototype.addEvent = function (event) {
  46585. this._events.push(event);
  46586. };
  46587. /**
  46588. * Remove all events found at the given frame
  46589. * @param frame
  46590. */
  46591. Animation.prototype.removeEvents = function (frame) {
  46592. for (var index = 0; index < this._events.length; index++) {
  46593. if (this._events[index].frame === frame) {
  46594. this._events.splice(index, 1);
  46595. index--;
  46596. }
  46597. }
  46598. };
  46599. Animation.prototype.getEvents = function () {
  46600. return this._events;
  46601. };
  46602. Animation.prototype.createRange = function (name, from, to) {
  46603. // check name not already in use; could happen for bones after serialized
  46604. if (!this._ranges[name]) {
  46605. this._ranges[name] = new AnimationRange(name, from, to);
  46606. }
  46607. };
  46608. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46609. if (deleteFrames === void 0) { deleteFrames = true; }
  46610. var range = this._ranges[name];
  46611. if (!range) {
  46612. return;
  46613. }
  46614. if (deleteFrames) {
  46615. var from = range.from;
  46616. var to = range.to;
  46617. // this loop MUST go high to low for multiple splices to work
  46618. for (var key = this._keys.length - 1; key >= 0; key--) {
  46619. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46620. this._keys.splice(key, 1);
  46621. }
  46622. }
  46623. }
  46624. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46625. };
  46626. Animation.prototype.getRange = function (name) {
  46627. return this._ranges[name];
  46628. };
  46629. Animation.prototype.getKeys = function () {
  46630. return this._keys;
  46631. };
  46632. Animation.prototype.getHighestFrame = function () {
  46633. var ret = 0;
  46634. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46635. if (ret < this._keys[key].frame) {
  46636. ret = this._keys[key].frame;
  46637. }
  46638. }
  46639. return ret;
  46640. };
  46641. Animation.prototype.getEasingFunction = function () {
  46642. return this._easingFunction;
  46643. };
  46644. Animation.prototype.setEasingFunction = function (easingFunction) {
  46645. this._easingFunction = easingFunction;
  46646. };
  46647. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46648. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46649. };
  46650. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46651. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46652. };
  46653. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46654. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46655. };
  46656. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46657. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46658. };
  46659. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46660. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46661. };
  46662. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46663. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46664. };
  46665. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46666. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46667. };
  46668. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46669. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46670. };
  46671. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46672. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46673. };
  46674. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46675. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46676. };
  46677. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46678. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46679. };
  46680. Animation.prototype.clone = function () {
  46681. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46682. clone.enableBlending = this.enableBlending;
  46683. clone.blendingSpeed = this.blendingSpeed;
  46684. if (this._keys) {
  46685. clone.setKeys(this._keys);
  46686. }
  46687. if (this._ranges) {
  46688. clone._ranges = {};
  46689. for (var name in this._ranges) {
  46690. var range = this._ranges[name];
  46691. if (!range) {
  46692. continue;
  46693. }
  46694. clone._ranges[name] = range.clone();
  46695. }
  46696. }
  46697. return clone;
  46698. };
  46699. Animation.prototype.setKeys = function (values) {
  46700. this._keys = values.slice(0);
  46701. };
  46702. Animation.prototype.serialize = function () {
  46703. var serializationObject = {};
  46704. serializationObject.name = this.name;
  46705. serializationObject.property = this.targetProperty;
  46706. serializationObject.framePerSecond = this.framePerSecond;
  46707. serializationObject.dataType = this.dataType;
  46708. serializationObject.loopBehavior = this.loopMode;
  46709. serializationObject.enableBlending = this.enableBlending;
  46710. serializationObject.blendingSpeed = this.blendingSpeed;
  46711. var dataType = this.dataType;
  46712. serializationObject.keys = [];
  46713. var keys = this.getKeys();
  46714. for (var index = 0; index < keys.length; index++) {
  46715. var animationKey = keys[index];
  46716. var key = {};
  46717. key.frame = animationKey.frame;
  46718. switch (dataType) {
  46719. case Animation.ANIMATIONTYPE_FLOAT:
  46720. key.values = [animationKey.value];
  46721. break;
  46722. case Animation.ANIMATIONTYPE_QUATERNION:
  46723. case Animation.ANIMATIONTYPE_MATRIX:
  46724. case Animation.ANIMATIONTYPE_VECTOR3:
  46725. case Animation.ANIMATIONTYPE_COLOR3:
  46726. key.values = animationKey.value.asArray();
  46727. break;
  46728. }
  46729. serializationObject.keys.push(key);
  46730. }
  46731. serializationObject.ranges = [];
  46732. for (var name in this._ranges) {
  46733. var source = this._ranges[name];
  46734. if (!source) {
  46735. continue;
  46736. }
  46737. var range = {};
  46738. range.name = name;
  46739. range.from = source.from;
  46740. range.to = source.to;
  46741. serializationObject.ranges.push(range);
  46742. }
  46743. return serializationObject;
  46744. };
  46745. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46746. get: function () {
  46747. return Animation._ANIMATIONTYPE_FLOAT;
  46748. },
  46749. enumerable: true,
  46750. configurable: true
  46751. });
  46752. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46753. get: function () {
  46754. return Animation._ANIMATIONTYPE_VECTOR3;
  46755. },
  46756. enumerable: true,
  46757. configurable: true
  46758. });
  46759. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46760. get: function () {
  46761. return Animation._ANIMATIONTYPE_VECTOR2;
  46762. },
  46763. enumerable: true,
  46764. configurable: true
  46765. });
  46766. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46767. get: function () {
  46768. return Animation._ANIMATIONTYPE_SIZE;
  46769. },
  46770. enumerable: true,
  46771. configurable: true
  46772. });
  46773. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46774. get: function () {
  46775. return Animation._ANIMATIONTYPE_QUATERNION;
  46776. },
  46777. enumerable: true,
  46778. configurable: true
  46779. });
  46780. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46781. get: function () {
  46782. return Animation._ANIMATIONTYPE_MATRIX;
  46783. },
  46784. enumerable: true,
  46785. configurable: true
  46786. });
  46787. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46788. get: function () {
  46789. return Animation._ANIMATIONTYPE_COLOR3;
  46790. },
  46791. enumerable: true,
  46792. configurable: true
  46793. });
  46794. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46795. get: function () {
  46796. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46797. },
  46798. enumerable: true,
  46799. configurable: true
  46800. });
  46801. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46802. get: function () {
  46803. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46804. },
  46805. enumerable: true,
  46806. configurable: true
  46807. });
  46808. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46809. get: function () {
  46810. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46811. },
  46812. enumerable: true,
  46813. configurable: true
  46814. });
  46815. Animation.Parse = function (parsedAnimation) {
  46816. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46817. var dataType = parsedAnimation.dataType;
  46818. var keys = [];
  46819. var data;
  46820. var index;
  46821. if (parsedAnimation.enableBlending) {
  46822. animation.enableBlending = parsedAnimation.enableBlending;
  46823. }
  46824. if (parsedAnimation.blendingSpeed) {
  46825. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46826. }
  46827. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46828. var key = parsedAnimation.keys[index];
  46829. var inTangent;
  46830. var outTangent;
  46831. switch (dataType) {
  46832. case Animation.ANIMATIONTYPE_FLOAT:
  46833. data = key.values[0];
  46834. if (key.values.length >= 1) {
  46835. inTangent = key.values[1];
  46836. }
  46837. if (key.values.length >= 2) {
  46838. outTangent = key.values[2];
  46839. }
  46840. break;
  46841. case Animation.ANIMATIONTYPE_QUATERNION:
  46842. data = BABYLON.Quaternion.FromArray(key.values);
  46843. if (key.values.length >= 8) {
  46844. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46845. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46846. inTangent = _inTangent;
  46847. }
  46848. }
  46849. if (key.values.length >= 12) {
  46850. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46851. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46852. outTangent = _outTangent;
  46853. }
  46854. }
  46855. break;
  46856. case Animation.ANIMATIONTYPE_MATRIX:
  46857. data = BABYLON.Matrix.FromArray(key.values);
  46858. break;
  46859. case Animation.ANIMATIONTYPE_COLOR3:
  46860. data = BABYLON.Color3.FromArray(key.values);
  46861. break;
  46862. case Animation.ANIMATIONTYPE_VECTOR3:
  46863. default:
  46864. data = BABYLON.Vector3.FromArray(key.values);
  46865. break;
  46866. }
  46867. var keyData = {};
  46868. keyData.frame = key.frame;
  46869. keyData.value = data;
  46870. if (inTangent != undefined) {
  46871. keyData.inTangent = inTangent;
  46872. }
  46873. if (outTangent != undefined) {
  46874. keyData.outTangent = outTangent;
  46875. }
  46876. keys.push(keyData);
  46877. }
  46878. animation.setKeys(keys);
  46879. if (parsedAnimation.ranges) {
  46880. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46881. data = parsedAnimation.ranges[index];
  46882. animation.createRange(data.name, data.from, data.to);
  46883. }
  46884. }
  46885. return animation;
  46886. };
  46887. Animation.AppendSerializedAnimations = function (source, destination) {
  46888. if (source.animations) {
  46889. destination.animations = [];
  46890. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46891. var animation = source.animations[animationIndex];
  46892. destination.animations.push(animation.serialize());
  46893. }
  46894. }
  46895. };
  46896. Animation.AllowMatricesInterpolation = false;
  46897. // Statics
  46898. Animation._ANIMATIONTYPE_FLOAT = 0;
  46899. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46900. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46901. Animation._ANIMATIONTYPE_MATRIX = 3;
  46902. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46903. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46904. Animation._ANIMATIONTYPE_SIZE = 6;
  46905. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46906. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46907. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46908. return Animation;
  46909. }());
  46910. BABYLON.Animation = Animation;
  46911. })(BABYLON || (BABYLON = {}));
  46912. //# sourceMappingURL=babylon.animation.js.map
  46913. var BABYLON;
  46914. (function (BABYLON) {
  46915. /**
  46916. * This class defines the direct association between an animation and a target
  46917. */
  46918. var TargetedAnimation = /** @class */ (function () {
  46919. function TargetedAnimation() {
  46920. }
  46921. return TargetedAnimation;
  46922. }());
  46923. BABYLON.TargetedAnimation = TargetedAnimation;
  46924. /**
  46925. * Use this class to create coordinated animations on multiple targets
  46926. */
  46927. var AnimationGroup = /** @class */ (function () {
  46928. function AnimationGroup(name, scene) {
  46929. if (scene === void 0) { scene = null; }
  46930. this.name = name;
  46931. this._targetedAnimations = new Array();
  46932. this._animatables = new Array();
  46933. this._from = Number.MAX_VALUE;
  46934. this._to = -Number.MAX_VALUE;
  46935. this._speedRatio = 1;
  46936. this.onAnimationEndObservable = new BABYLON.Observable();
  46937. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46938. this._scene.animationGroups.push(this);
  46939. }
  46940. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46941. /**
  46942. * Define if the animations are started
  46943. */
  46944. get: function () {
  46945. return this._isStarted;
  46946. },
  46947. enumerable: true,
  46948. configurable: true
  46949. });
  46950. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46951. /**
  46952. * Gets or sets the speed ratio to use for all animations
  46953. */
  46954. get: function () {
  46955. return this._speedRatio;
  46956. },
  46957. /**
  46958. * Gets or sets the speed ratio to use for all animations
  46959. */
  46960. set: function (value) {
  46961. if (this._speedRatio === value) {
  46962. return;
  46963. }
  46964. this._speedRatio = value;
  46965. for (var index = 0; index < this._animatables.length; index++) {
  46966. var animatable = this._animatables[index];
  46967. animatable.speedRatio = this._speedRatio;
  46968. }
  46969. },
  46970. enumerable: true,
  46971. configurable: true
  46972. });
  46973. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46974. /**
  46975. * Gets the targeted animations for this animation group
  46976. */
  46977. get: function () {
  46978. return this._targetedAnimations;
  46979. },
  46980. enumerable: true,
  46981. configurable: true
  46982. });
  46983. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  46984. /**
  46985. * returning the list of animatables controlled by this animation group.
  46986. */
  46987. get: function () {
  46988. return this._animatables;
  46989. },
  46990. enumerable: true,
  46991. configurable: true
  46992. });
  46993. /**
  46994. * Add an animation (with its target) in the group
  46995. * @param animation defines the animation we want to add
  46996. * @param target defines the target of the animation
  46997. * @returns the {BABYLON.TargetedAnimation} object
  46998. */
  46999. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47000. var targetedAnimation = {
  47001. animation: animation,
  47002. target: target
  47003. };
  47004. var keys = animation.getKeys();
  47005. if (this._from > keys[0].frame) {
  47006. this._from = keys[0].frame;
  47007. }
  47008. if (this._to < keys[keys.length - 1].frame) {
  47009. this._to = keys[keys.length - 1].frame;
  47010. }
  47011. this._targetedAnimations.push(targetedAnimation);
  47012. return targetedAnimation;
  47013. };
  47014. /**
  47015. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47016. * It can add constant keys at begin or end
  47017. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47018. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47019. */
  47020. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47021. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47022. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47023. beginFrame = Math.max(beginFrame, this._from);
  47024. endFrame = Math.min(endFrame, this._to);
  47025. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47026. var targetedAnimation = this._targetedAnimations[index];
  47027. var keys = targetedAnimation.animation.getKeys();
  47028. var startKey = keys[0];
  47029. var endKey = keys[keys.length - 1];
  47030. if (startKey.frame > beginFrame) {
  47031. var newKey = {
  47032. frame: beginFrame,
  47033. value: startKey.value,
  47034. inTangent: startKey.inTangent,
  47035. outTangent: startKey.outTangent,
  47036. interpolation: startKey.interpolation
  47037. };
  47038. keys.splice(0, 0, newKey);
  47039. }
  47040. if (endKey.frame < endFrame) {
  47041. var newKey = {
  47042. frame: endFrame,
  47043. value: endKey.value,
  47044. inTangent: endKey.outTangent,
  47045. outTangent: endKey.outTangent,
  47046. interpolation: endKey.interpolation
  47047. };
  47048. keys.push(newKey);
  47049. }
  47050. }
  47051. return this;
  47052. };
  47053. /**
  47054. * Start all animations on given targets
  47055. * @param loop defines if animations must loop
  47056. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47057. */
  47058. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47059. var _this = this;
  47060. if (loop === void 0) { loop = false; }
  47061. if (speedRatio === void 0) { speedRatio = 1; }
  47062. if (this._isStarted || this._targetedAnimations.length === 0) {
  47063. return this;
  47064. }
  47065. var _loop_1 = function () {
  47066. var targetedAnimation = this_1._targetedAnimations[index];
  47067. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47068. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47069. }));
  47070. };
  47071. var this_1 = this;
  47072. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47073. _loop_1();
  47074. }
  47075. this._speedRatio = speedRatio;
  47076. this._isStarted = true;
  47077. return this;
  47078. };
  47079. /**
  47080. * Pause all animations
  47081. */
  47082. AnimationGroup.prototype.pause = function () {
  47083. if (!this._isStarted) {
  47084. return this;
  47085. }
  47086. for (var index = 0; index < this._animatables.length; index++) {
  47087. var animatable = this._animatables[index];
  47088. animatable.pause();
  47089. }
  47090. return this;
  47091. };
  47092. /**
  47093. * Play all animations to initial state
  47094. * This function will start() the animations if they were not started or will restart() them if they were paused
  47095. * @param loop defines if animations must loop
  47096. */
  47097. AnimationGroup.prototype.play = function (loop) {
  47098. if (this.isStarted) {
  47099. if (loop !== undefined) {
  47100. for (var index = 0; index < this._animatables.length; index++) {
  47101. var animatable = this._animatables[index];
  47102. animatable.loopAnimation = loop;
  47103. }
  47104. }
  47105. this.restart();
  47106. }
  47107. else {
  47108. this.start(loop, this._speedRatio);
  47109. }
  47110. return this;
  47111. };
  47112. /**
  47113. * Reset all animations to initial state
  47114. */
  47115. AnimationGroup.prototype.reset = function () {
  47116. if (!this._isStarted) {
  47117. return this;
  47118. }
  47119. for (var index = 0; index < this._animatables.length; index++) {
  47120. var animatable = this._animatables[index];
  47121. animatable.reset();
  47122. }
  47123. return this;
  47124. };
  47125. /**
  47126. * Restart animations from key 0
  47127. */
  47128. AnimationGroup.prototype.restart = function () {
  47129. if (!this._isStarted) {
  47130. return this;
  47131. }
  47132. for (var index = 0; index < this._animatables.length; index++) {
  47133. var animatable = this._animatables[index];
  47134. animatable.restart();
  47135. }
  47136. return this;
  47137. };
  47138. /**
  47139. * Stop all animations
  47140. */
  47141. AnimationGroup.prototype.stop = function () {
  47142. if (!this._isStarted) {
  47143. return this;
  47144. }
  47145. for (var index = 0; index < this._animatables.length; index++) {
  47146. var animatable = this._animatables[index];
  47147. animatable.stop();
  47148. }
  47149. this._isStarted = false;
  47150. return this;
  47151. };
  47152. /**
  47153. * Goes to a specific frame in this animation group
  47154. *
  47155. * @param frame the frame number to go to
  47156. * @return the animationGroup
  47157. */
  47158. AnimationGroup.prototype.goToFrame = function (frame) {
  47159. if (!this._isStarted) {
  47160. return this;
  47161. }
  47162. for (var index = 0; index < this._animatables.length; index++) {
  47163. var animatable = this._animatables[index];
  47164. animatable.goToFrame(frame);
  47165. }
  47166. return this;
  47167. };
  47168. /**
  47169. * Dispose all associated resources
  47170. */
  47171. AnimationGroup.prototype.dispose = function () {
  47172. this._targetedAnimations = [];
  47173. this._animatables = [];
  47174. var index = this._scene.animationGroups.indexOf(this);
  47175. if (index > -1) {
  47176. this._scene.animationGroups.splice(index, 1);
  47177. }
  47178. };
  47179. return AnimationGroup;
  47180. }());
  47181. BABYLON.AnimationGroup = AnimationGroup;
  47182. })(BABYLON || (BABYLON = {}));
  47183. //# sourceMappingURL=babylon.animationGroup.js.map
  47184. var BABYLON;
  47185. (function (BABYLON) {
  47186. var RuntimeAnimation = /** @class */ (function () {
  47187. function RuntimeAnimation(target, animation) {
  47188. this._offsetsCache = {};
  47189. this._highLimitsCache = {};
  47190. this._stopped = false;
  47191. this._blendingFactor = 0;
  47192. this._ratioOffset = 0;
  47193. this._animation = animation;
  47194. this._target = target;
  47195. animation._runtimeAnimations.push(this);
  47196. }
  47197. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47198. get: function () {
  47199. return this._animation;
  47200. },
  47201. enumerable: true,
  47202. configurable: true
  47203. });
  47204. RuntimeAnimation.prototype.reset = function () {
  47205. this._offsetsCache = {};
  47206. this._highLimitsCache = {};
  47207. this.currentFrame = 0;
  47208. this._blendingFactor = 0;
  47209. this._originalBlendValue = null;
  47210. };
  47211. RuntimeAnimation.prototype.isStopped = function () {
  47212. return this._stopped;
  47213. };
  47214. RuntimeAnimation.prototype.dispose = function () {
  47215. var index = this._animation.runtimeAnimations.indexOf(this);
  47216. if (index > -1) {
  47217. this._animation.runtimeAnimations.splice(index, 1);
  47218. }
  47219. };
  47220. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47221. if (typeof value === "function") {
  47222. return value();
  47223. }
  47224. return value;
  47225. };
  47226. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47227. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47228. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47229. }
  47230. this.currentFrame = currentFrame;
  47231. var keys = this._animation.getKeys();
  47232. // Try to get a hash to find the right key
  47233. 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));
  47234. if (keys[startKeyIndex].frame >= currentFrame) {
  47235. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47236. startKeyIndex--;
  47237. }
  47238. }
  47239. for (var key = startKeyIndex; key < keys.length; key++) {
  47240. var endKey = keys[key + 1];
  47241. if (endKey.frame >= currentFrame) {
  47242. var startKey = keys[key];
  47243. var startValue = this._getKeyValue(startKey.value);
  47244. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47245. return startValue;
  47246. }
  47247. var endValue = this._getKeyValue(endKey.value);
  47248. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47249. var frameDelta = endKey.frame - startKey.frame;
  47250. // gradient : percent of currentFrame between the frame inf and the frame sup
  47251. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47252. // check for easingFunction and correction of gradient
  47253. var easingFunction = this._animation.getEasingFunction();
  47254. if (easingFunction != null) {
  47255. gradient = easingFunction.ease(gradient);
  47256. }
  47257. switch (this._animation.dataType) {
  47258. // Float
  47259. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47260. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47261. switch (loopMode) {
  47262. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47263. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47264. return floatValue;
  47265. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47266. return offsetValue * repeatCount + floatValue;
  47267. }
  47268. break;
  47269. // Quaternion
  47270. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47271. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47272. switch (loopMode) {
  47273. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47274. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47275. return quatValue;
  47276. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47277. return quatValue.add(offsetValue.scale(repeatCount));
  47278. }
  47279. return quatValue;
  47280. // Vector3
  47281. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47282. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47283. switch (loopMode) {
  47284. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47285. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47286. return vec3Value;
  47287. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47288. return vec3Value.add(offsetValue.scale(repeatCount));
  47289. }
  47290. // Vector2
  47291. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47292. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47293. switch (loopMode) {
  47294. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47295. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47296. return vec2Value;
  47297. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47298. return vec2Value.add(offsetValue.scale(repeatCount));
  47299. }
  47300. // Size
  47301. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47302. switch (loopMode) {
  47303. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47304. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47305. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47306. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47307. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47308. }
  47309. // Color3
  47310. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47311. switch (loopMode) {
  47312. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47313. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47314. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47315. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47316. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47317. }
  47318. // Matrix
  47319. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47320. switch (loopMode) {
  47321. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47322. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47323. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47324. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47325. }
  47326. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47327. return startValue;
  47328. }
  47329. default:
  47330. break;
  47331. }
  47332. break;
  47333. }
  47334. }
  47335. return this._getKeyValue(keys[keys.length - 1].value);
  47336. };
  47337. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47338. if (blend === void 0) { blend = false; }
  47339. // Set value
  47340. var path;
  47341. var destination;
  47342. var targetPropertyPath = this._animation.targetPropertyPath;
  47343. if (targetPropertyPath.length > 1) {
  47344. var property = this._target[targetPropertyPath[0]];
  47345. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47346. property = property[targetPropertyPath[index]];
  47347. }
  47348. path = targetPropertyPath[targetPropertyPath.length - 1];
  47349. destination = property;
  47350. }
  47351. else {
  47352. path = targetPropertyPath[0];
  47353. destination = this._target;
  47354. }
  47355. // Blending
  47356. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47357. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47358. if (enableBlending && this._blendingFactor <= 1.0) {
  47359. if (!this._originalBlendValue) {
  47360. if (destination[path].clone) {
  47361. this._originalBlendValue = destination[path].clone();
  47362. }
  47363. else {
  47364. this._originalBlendValue = destination[path];
  47365. }
  47366. }
  47367. if (this._originalBlendValue.prototype) {
  47368. if (this._originalBlendValue.prototype.Lerp) {
  47369. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47370. }
  47371. else {
  47372. destination[path] = currentValue;
  47373. }
  47374. }
  47375. else if (this._originalBlendValue.m) {
  47376. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47377. }
  47378. else {
  47379. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47380. }
  47381. this._blendingFactor += blendingSpeed;
  47382. }
  47383. else {
  47384. destination[path] = currentValue;
  47385. }
  47386. if (this._target.markAsDirty) {
  47387. this._target.markAsDirty(this._animation.targetProperty);
  47388. }
  47389. };
  47390. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47391. if (this._target && this._target.animationPropertiesOverride) {
  47392. return this._target.animationPropertiesOverride.loopMode;
  47393. }
  47394. return this._animation.loopMode;
  47395. };
  47396. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47397. var keys = this._animation.getKeys();
  47398. if (frame < keys[0].frame) {
  47399. frame = keys[0].frame;
  47400. }
  47401. else if (frame > keys[keys.length - 1].frame) {
  47402. frame = keys[keys.length - 1].frame;
  47403. }
  47404. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47405. this.setValue(currentValue);
  47406. };
  47407. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47408. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47409. this._ratioOffset = this._previousRatio - newRatio;
  47410. };
  47411. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47412. if (blend === void 0) { blend = false; }
  47413. var targetPropertyPath = this._animation.targetPropertyPath;
  47414. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47415. this._stopped = true;
  47416. return false;
  47417. }
  47418. var returnValue = true;
  47419. var keys = this._animation.getKeys();
  47420. // Adding a start key at frame 0 if missing
  47421. if (keys[0].frame !== 0) {
  47422. var newKey = { frame: 0, value: keys[0].value };
  47423. keys.splice(0, 0, newKey);
  47424. }
  47425. // Check limits
  47426. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47427. from = keys[0].frame;
  47428. }
  47429. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47430. to = keys[keys.length - 1].frame;
  47431. }
  47432. //to and from cannot be the same key
  47433. if (from === to) {
  47434. if (from > keys[0].frame) {
  47435. from--;
  47436. }
  47437. else if (to < keys[keys.length - 1].frame) {
  47438. to++;
  47439. }
  47440. }
  47441. // Compute ratio
  47442. var range = to - from;
  47443. var offsetValue;
  47444. // ratio represents the frame delta between from and to
  47445. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47446. var highLimitValue = 0;
  47447. this._previousDelay = delay;
  47448. this._previousRatio = ratio;
  47449. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47450. returnValue = false;
  47451. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47452. }
  47453. else {
  47454. // Get max value if required
  47455. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47456. var keyOffset = to.toString() + from.toString();
  47457. if (!this._offsetsCache[keyOffset]) {
  47458. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47459. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47460. switch (this._animation.dataType) {
  47461. // Float
  47462. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47463. this._offsetsCache[keyOffset] = toValue - fromValue;
  47464. break;
  47465. // Quaternion
  47466. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47467. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47468. break;
  47469. // Vector3
  47470. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47471. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47472. // Vector2
  47473. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47474. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47475. // Size
  47476. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47477. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47478. // Color3
  47479. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47480. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47481. default:
  47482. break;
  47483. }
  47484. this._highLimitsCache[keyOffset] = toValue;
  47485. }
  47486. highLimitValue = this._highLimitsCache[keyOffset];
  47487. offsetValue = this._offsetsCache[keyOffset];
  47488. }
  47489. }
  47490. if (offsetValue === undefined) {
  47491. switch (this._animation.dataType) {
  47492. // Float
  47493. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47494. offsetValue = 0;
  47495. break;
  47496. // Quaternion
  47497. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47498. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47499. break;
  47500. // Vector3
  47501. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47502. offsetValue = BABYLON.Vector3.Zero();
  47503. break;
  47504. // Vector2
  47505. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47506. offsetValue = BABYLON.Vector2.Zero();
  47507. break;
  47508. // Size
  47509. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47510. offsetValue = BABYLON.Size.Zero();
  47511. break;
  47512. // Color3
  47513. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47514. offsetValue = BABYLON.Color3.Black();
  47515. }
  47516. }
  47517. // Compute value
  47518. var repeatCount = (ratio / range) >> 0;
  47519. var currentFrame = returnValue ? from + ratio % range : to;
  47520. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47521. // Set value
  47522. this.setValue(currentValue);
  47523. // Check events
  47524. var events = this._animation.getEvents();
  47525. for (var index = 0; index < events.length; index++) {
  47526. // Make sure current frame has passed event frame and that event frame is within the current range
  47527. // Also, handle both forward and reverse animations
  47528. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47529. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47530. var event = events[index];
  47531. if (!event.isDone) {
  47532. // If event should be done only once, remove it.
  47533. if (event.onlyOnce) {
  47534. events.splice(index, 1);
  47535. index--;
  47536. }
  47537. event.isDone = true;
  47538. event.action();
  47539. } // Don't do anything if the event has already be done.
  47540. }
  47541. else if (events[index].isDone && !events[index].onlyOnce) {
  47542. // reset event, the animation is looping
  47543. events[index].isDone = false;
  47544. }
  47545. }
  47546. if (!returnValue) {
  47547. this._stopped = true;
  47548. }
  47549. return returnValue;
  47550. };
  47551. return RuntimeAnimation;
  47552. }());
  47553. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47554. })(BABYLON || (BABYLON = {}));
  47555. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47556. var BABYLON;
  47557. (function (BABYLON) {
  47558. var Animatable = /** @class */ (function () {
  47559. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47560. if (fromFrame === void 0) { fromFrame = 0; }
  47561. if (toFrame === void 0) { toFrame = 100; }
  47562. if (loopAnimation === void 0) { loopAnimation = false; }
  47563. if (speedRatio === void 0) { speedRatio = 1.0; }
  47564. this.target = target;
  47565. this.fromFrame = fromFrame;
  47566. this.toFrame = toFrame;
  47567. this.loopAnimation = loopAnimation;
  47568. this.onAnimationEnd = onAnimationEnd;
  47569. this._localDelayOffset = null;
  47570. this._pausedDelay = null;
  47571. this._runtimeAnimations = new Array();
  47572. this._paused = false;
  47573. this._speedRatio = 1;
  47574. this.animationStarted = false;
  47575. if (animations) {
  47576. this.appendAnimations(target, animations);
  47577. }
  47578. this._speedRatio = speedRatio;
  47579. this._scene = scene;
  47580. scene._activeAnimatables.push(this);
  47581. }
  47582. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47583. get: function () {
  47584. return this._speedRatio;
  47585. },
  47586. set: function (value) {
  47587. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47588. var animation = this._runtimeAnimations[index];
  47589. animation._prepareForSpeedRatioChange(value);
  47590. }
  47591. this._speedRatio = value;
  47592. },
  47593. enumerable: true,
  47594. configurable: true
  47595. });
  47596. // Methods
  47597. Animatable.prototype.getAnimations = function () {
  47598. return this._runtimeAnimations;
  47599. };
  47600. Animatable.prototype.appendAnimations = function (target, animations) {
  47601. for (var index = 0; index < animations.length; index++) {
  47602. var animation = animations[index];
  47603. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47604. }
  47605. };
  47606. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47607. var runtimeAnimations = this._runtimeAnimations;
  47608. for (var index = 0; index < runtimeAnimations.length; index++) {
  47609. if (runtimeAnimations[index].animation.targetProperty === property) {
  47610. return runtimeAnimations[index].animation;
  47611. }
  47612. }
  47613. return null;
  47614. };
  47615. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47616. var runtimeAnimations = this._runtimeAnimations;
  47617. for (var index = 0; index < runtimeAnimations.length; index++) {
  47618. if (runtimeAnimations[index].animation.targetProperty === property) {
  47619. return runtimeAnimations[index];
  47620. }
  47621. }
  47622. return null;
  47623. };
  47624. Animatable.prototype.reset = function () {
  47625. var runtimeAnimations = this._runtimeAnimations;
  47626. for (var index = 0; index < runtimeAnimations.length; index++) {
  47627. runtimeAnimations[index].reset();
  47628. }
  47629. // Reset to original value
  47630. for (index = 0; index < runtimeAnimations.length; index++) {
  47631. var animation = runtimeAnimations[index];
  47632. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47633. }
  47634. this._localDelayOffset = null;
  47635. this._pausedDelay = null;
  47636. };
  47637. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47638. var runtimeAnimations = this._runtimeAnimations;
  47639. for (var index = 0; index < runtimeAnimations.length; index++) {
  47640. runtimeAnimations[index].animation.enableBlending = true;
  47641. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47642. }
  47643. };
  47644. Animatable.prototype.disableBlending = function () {
  47645. var runtimeAnimations = this._runtimeAnimations;
  47646. for (var index = 0; index < runtimeAnimations.length; index++) {
  47647. runtimeAnimations[index].animation.enableBlending = false;
  47648. }
  47649. };
  47650. Animatable.prototype.goToFrame = function (frame) {
  47651. var runtimeAnimations = this._runtimeAnimations;
  47652. if (runtimeAnimations[0]) {
  47653. var fps = runtimeAnimations[0].animation.framePerSecond;
  47654. var currentFrame = runtimeAnimations[0].currentFrame;
  47655. var adjustTime = frame - currentFrame;
  47656. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47657. if (this._localDelayOffset === null) {
  47658. this._localDelayOffset = 0;
  47659. }
  47660. this._localDelayOffset -= delay;
  47661. }
  47662. for (var index = 0; index < runtimeAnimations.length; index++) {
  47663. runtimeAnimations[index].goToFrame(frame);
  47664. }
  47665. };
  47666. Animatable.prototype.pause = function () {
  47667. if (this._paused) {
  47668. return;
  47669. }
  47670. this._paused = true;
  47671. };
  47672. Animatable.prototype.restart = function () {
  47673. this._paused = false;
  47674. };
  47675. Animatable.prototype.stop = function (animationName) {
  47676. if (animationName) {
  47677. var idx = this._scene._activeAnimatables.indexOf(this);
  47678. if (idx > -1) {
  47679. var runtimeAnimations = this._runtimeAnimations;
  47680. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47681. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47682. continue;
  47683. }
  47684. runtimeAnimations[index].dispose();
  47685. runtimeAnimations.splice(index, 1);
  47686. }
  47687. if (runtimeAnimations.length == 0) {
  47688. this._scene._activeAnimatables.splice(idx, 1);
  47689. if (this.onAnimationEnd) {
  47690. this.onAnimationEnd();
  47691. }
  47692. }
  47693. }
  47694. }
  47695. else {
  47696. var index = this._scene._activeAnimatables.indexOf(this);
  47697. if (index > -1) {
  47698. this._scene._activeAnimatables.splice(index, 1);
  47699. var runtimeAnimations = this._runtimeAnimations;
  47700. for (var index = 0; index < runtimeAnimations.length; index++) {
  47701. runtimeAnimations[index].dispose();
  47702. }
  47703. if (this.onAnimationEnd) {
  47704. this.onAnimationEnd();
  47705. }
  47706. }
  47707. }
  47708. };
  47709. Animatable.prototype._animate = function (delay) {
  47710. if (this._paused) {
  47711. this.animationStarted = false;
  47712. if (this._pausedDelay === null) {
  47713. this._pausedDelay = delay;
  47714. }
  47715. return true;
  47716. }
  47717. if (this._localDelayOffset === null) {
  47718. this._localDelayOffset = delay;
  47719. this._pausedDelay = null;
  47720. }
  47721. else if (this._pausedDelay !== null) {
  47722. this._localDelayOffset += delay - this._pausedDelay;
  47723. this._pausedDelay = null;
  47724. }
  47725. // Animating
  47726. var running = false;
  47727. var runtimeAnimations = this._runtimeAnimations;
  47728. var index;
  47729. for (index = 0; index < runtimeAnimations.length; index++) {
  47730. var animation = runtimeAnimations[index];
  47731. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47732. running = running || isRunning;
  47733. }
  47734. this.animationStarted = running;
  47735. if (!running) {
  47736. // Remove from active animatables
  47737. index = this._scene._activeAnimatables.indexOf(this);
  47738. this._scene._activeAnimatables.splice(index, 1);
  47739. // Dispose all runtime animations
  47740. for (index = 0; index < runtimeAnimations.length; index++) {
  47741. runtimeAnimations[index].dispose();
  47742. }
  47743. }
  47744. if (!running && this.onAnimationEnd) {
  47745. this.onAnimationEnd();
  47746. this.onAnimationEnd = null;
  47747. }
  47748. return running;
  47749. };
  47750. return Animatable;
  47751. }());
  47752. BABYLON.Animatable = Animatable;
  47753. })(BABYLON || (BABYLON = {}));
  47754. //# sourceMappingURL=babylon.animatable.js.map
  47755. var BABYLON;
  47756. (function (BABYLON) {
  47757. var EasingFunction = /** @class */ (function () {
  47758. function EasingFunction() {
  47759. // Properties
  47760. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47761. }
  47762. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47763. get: function () {
  47764. return EasingFunction._EASINGMODE_EASEIN;
  47765. },
  47766. enumerable: true,
  47767. configurable: true
  47768. });
  47769. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47770. get: function () {
  47771. return EasingFunction._EASINGMODE_EASEOUT;
  47772. },
  47773. enumerable: true,
  47774. configurable: true
  47775. });
  47776. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47777. get: function () {
  47778. return EasingFunction._EASINGMODE_EASEINOUT;
  47779. },
  47780. enumerable: true,
  47781. configurable: true
  47782. });
  47783. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47784. var n = Math.min(Math.max(easingMode, 0), 2);
  47785. this._easingMode = n;
  47786. };
  47787. EasingFunction.prototype.getEasingMode = function () {
  47788. return this._easingMode;
  47789. };
  47790. EasingFunction.prototype.easeInCore = function (gradient) {
  47791. throw new Error('You must implement this method');
  47792. };
  47793. EasingFunction.prototype.ease = function (gradient) {
  47794. switch (this._easingMode) {
  47795. case EasingFunction.EASINGMODE_EASEIN:
  47796. return this.easeInCore(gradient);
  47797. case EasingFunction.EASINGMODE_EASEOUT:
  47798. return (1 - this.easeInCore(1 - gradient));
  47799. }
  47800. if (gradient >= 0.5) {
  47801. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47802. }
  47803. return (this.easeInCore(gradient * 2) * 0.5);
  47804. };
  47805. //Statics
  47806. EasingFunction._EASINGMODE_EASEIN = 0;
  47807. EasingFunction._EASINGMODE_EASEOUT = 1;
  47808. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47809. return EasingFunction;
  47810. }());
  47811. BABYLON.EasingFunction = EasingFunction;
  47812. var CircleEase = /** @class */ (function (_super) {
  47813. __extends(CircleEase, _super);
  47814. function CircleEase() {
  47815. return _super !== null && _super.apply(this, arguments) || this;
  47816. }
  47817. CircleEase.prototype.easeInCore = function (gradient) {
  47818. gradient = Math.max(0, Math.min(1, gradient));
  47819. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47820. };
  47821. return CircleEase;
  47822. }(EasingFunction));
  47823. BABYLON.CircleEase = CircleEase;
  47824. var BackEase = /** @class */ (function (_super) {
  47825. __extends(BackEase, _super);
  47826. function BackEase(amplitude) {
  47827. if (amplitude === void 0) { amplitude = 1; }
  47828. var _this = _super.call(this) || this;
  47829. _this.amplitude = amplitude;
  47830. return _this;
  47831. }
  47832. BackEase.prototype.easeInCore = function (gradient) {
  47833. var num = Math.max(0, this.amplitude);
  47834. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47835. };
  47836. return BackEase;
  47837. }(EasingFunction));
  47838. BABYLON.BackEase = BackEase;
  47839. var BounceEase = /** @class */ (function (_super) {
  47840. __extends(BounceEase, _super);
  47841. function BounceEase(bounces, bounciness) {
  47842. if (bounces === void 0) { bounces = 3; }
  47843. if (bounciness === void 0) { bounciness = 2; }
  47844. var _this = _super.call(this) || this;
  47845. _this.bounces = bounces;
  47846. _this.bounciness = bounciness;
  47847. return _this;
  47848. }
  47849. BounceEase.prototype.easeInCore = function (gradient) {
  47850. var y = Math.max(0.0, this.bounces);
  47851. var bounciness = this.bounciness;
  47852. if (bounciness <= 1.0) {
  47853. bounciness = 1.001;
  47854. }
  47855. var num9 = Math.pow(bounciness, y);
  47856. var num5 = 1.0 - bounciness;
  47857. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47858. var num15 = gradient * num4;
  47859. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47860. var num3 = Math.floor(num65);
  47861. var num13 = num3 + 1.0;
  47862. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47863. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47864. var num7 = (num8 + num12) * 0.5;
  47865. var num6 = gradient - num7;
  47866. var num2 = num7 - num8;
  47867. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47868. };
  47869. return BounceEase;
  47870. }(EasingFunction));
  47871. BABYLON.BounceEase = BounceEase;
  47872. var CubicEase = /** @class */ (function (_super) {
  47873. __extends(CubicEase, _super);
  47874. function CubicEase() {
  47875. return _super !== null && _super.apply(this, arguments) || this;
  47876. }
  47877. CubicEase.prototype.easeInCore = function (gradient) {
  47878. return (gradient * gradient * gradient);
  47879. };
  47880. return CubicEase;
  47881. }(EasingFunction));
  47882. BABYLON.CubicEase = CubicEase;
  47883. var ElasticEase = /** @class */ (function (_super) {
  47884. __extends(ElasticEase, _super);
  47885. function ElasticEase(oscillations, springiness) {
  47886. if (oscillations === void 0) { oscillations = 3; }
  47887. if (springiness === void 0) { springiness = 3; }
  47888. var _this = _super.call(this) || this;
  47889. _this.oscillations = oscillations;
  47890. _this.springiness = springiness;
  47891. return _this;
  47892. }
  47893. ElasticEase.prototype.easeInCore = function (gradient) {
  47894. var num2;
  47895. var num3 = Math.max(0.0, this.oscillations);
  47896. var num = Math.max(0.0, this.springiness);
  47897. if (num == 0) {
  47898. num2 = gradient;
  47899. }
  47900. else {
  47901. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47902. }
  47903. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47904. };
  47905. return ElasticEase;
  47906. }(EasingFunction));
  47907. BABYLON.ElasticEase = ElasticEase;
  47908. var ExponentialEase = /** @class */ (function (_super) {
  47909. __extends(ExponentialEase, _super);
  47910. function ExponentialEase(exponent) {
  47911. if (exponent === void 0) { exponent = 2; }
  47912. var _this = _super.call(this) || this;
  47913. _this.exponent = exponent;
  47914. return _this;
  47915. }
  47916. ExponentialEase.prototype.easeInCore = function (gradient) {
  47917. if (this.exponent <= 0) {
  47918. return gradient;
  47919. }
  47920. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47921. };
  47922. return ExponentialEase;
  47923. }(EasingFunction));
  47924. BABYLON.ExponentialEase = ExponentialEase;
  47925. var PowerEase = /** @class */ (function (_super) {
  47926. __extends(PowerEase, _super);
  47927. function PowerEase(power) {
  47928. if (power === void 0) { power = 2; }
  47929. var _this = _super.call(this) || this;
  47930. _this.power = power;
  47931. return _this;
  47932. }
  47933. PowerEase.prototype.easeInCore = function (gradient) {
  47934. var y = Math.max(0.0, this.power);
  47935. return Math.pow(gradient, y);
  47936. };
  47937. return PowerEase;
  47938. }(EasingFunction));
  47939. BABYLON.PowerEase = PowerEase;
  47940. var QuadraticEase = /** @class */ (function (_super) {
  47941. __extends(QuadraticEase, _super);
  47942. function QuadraticEase() {
  47943. return _super !== null && _super.apply(this, arguments) || this;
  47944. }
  47945. QuadraticEase.prototype.easeInCore = function (gradient) {
  47946. return (gradient * gradient);
  47947. };
  47948. return QuadraticEase;
  47949. }(EasingFunction));
  47950. BABYLON.QuadraticEase = QuadraticEase;
  47951. var QuarticEase = /** @class */ (function (_super) {
  47952. __extends(QuarticEase, _super);
  47953. function QuarticEase() {
  47954. return _super !== null && _super.apply(this, arguments) || this;
  47955. }
  47956. QuarticEase.prototype.easeInCore = function (gradient) {
  47957. return (gradient * gradient * gradient * gradient);
  47958. };
  47959. return QuarticEase;
  47960. }(EasingFunction));
  47961. BABYLON.QuarticEase = QuarticEase;
  47962. var QuinticEase = /** @class */ (function (_super) {
  47963. __extends(QuinticEase, _super);
  47964. function QuinticEase() {
  47965. return _super !== null && _super.apply(this, arguments) || this;
  47966. }
  47967. QuinticEase.prototype.easeInCore = function (gradient) {
  47968. return (gradient * gradient * gradient * gradient * gradient);
  47969. };
  47970. return QuinticEase;
  47971. }(EasingFunction));
  47972. BABYLON.QuinticEase = QuinticEase;
  47973. var SineEase = /** @class */ (function (_super) {
  47974. __extends(SineEase, _super);
  47975. function SineEase() {
  47976. return _super !== null && _super.apply(this, arguments) || this;
  47977. }
  47978. SineEase.prototype.easeInCore = function (gradient) {
  47979. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47980. };
  47981. return SineEase;
  47982. }(EasingFunction));
  47983. BABYLON.SineEase = SineEase;
  47984. var BezierCurveEase = /** @class */ (function (_super) {
  47985. __extends(BezierCurveEase, _super);
  47986. function BezierCurveEase(x1, y1, x2, y2) {
  47987. if (x1 === void 0) { x1 = 0; }
  47988. if (y1 === void 0) { y1 = 0; }
  47989. if (x2 === void 0) { x2 = 1; }
  47990. if (y2 === void 0) { y2 = 1; }
  47991. var _this = _super.call(this) || this;
  47992. _this.x1 = x1;
  47993. _this.y1 = y1;
  47994. _this.x2 = x2;
  47995. _this.y2 = y2;
  47996. return _this;
  47997. }
  47998. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47999. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48000. };
  48001. return BezierCurveEase;
  48002. }(EasingFunction));
  48003. BABYLON.BezierCurveEase = BezierCurveEase;
  48004. })(BABYLON || (BABYLON = {}));
  48005. //# sourceMappingURL=babylon.easing.js.map
  48006. var BABYLON;
  48007. (function (BABYLON) {
  48008. var Condition = /** @class */ (function () {
  48009. function Condition(actionManager) {
  48010. this._actionManager = actionManager;
  48011. }
  48012. Condition.prototype.isValid = function () {
  48013. return true;
  48014. };
  48015. Condition.prototype._getProperty = function (propertyPath) {
  48016. return this._actionManager._getProperty(propertyPath);
  48017. };
  48018. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48019. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48020. };
  48021. Condition.prototype.serialize = function () {
  48022. };
  48023. Condition.prototype._serialize = function (serializedCondition) {
  48024. return {
  48025. type: 2,
  48026. children: [],
  48027. name: serializedCondition.name,
  48028. properties: serializedCondition.properties
  48029. };
  48030. };
  48031. return Condition;
  48032. }());
  48033. BABYLON.Condition = Condition;
  48034. var ValueCondition = /** @class */ (function (_super) {
  48035. __extends(ValueCondition, _super);
  48036. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48037. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48038. var _this = _super.call(this, actionManager) || this;
  48039. _this.propertyPath = propertyPath;
  48040. _this.value = value;
  48041. _this.operator = operator;
  48042. _this._target = target;
  48043. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48044. _this._property = _this._getProperty(_this.propertyPath);
  48045. return _this;
  48046. }
  48047. Object.defineProperty(ValueCondition, "IsEqual", {
  48048. get: function () {
  48049. return ValueCondition._IsEqual;
  48050. },
  48051. enumerable: true,
  48052. configurable: true
  48053. });
  48054. Object.defineProperty(ValueCondition, "IsDifferent", {
  48055. get: function () {
  48056. return ValueCondition._IsDifferent;
  48057. },
  48058. enumerable: true,
  48059. configurable: true
  48060. });
  48061. Object.defineProperty(ValueCondition, "IsGreater", {
  48062. get: function () {
  48063. return ValueCondition._IsGreater;
  48064. },
  48065. enumerable: true,
  48066. configurable: true
  48067. });
  48068. Object.defineProperty(ValueCondition, "IsLesser", {
  48069. get: function () {
  48070. return ValueCondition._IsLesser;
  48071. },
  48072. enumerable: true,
  48073. configurable: true
  48074. });
  48075. // Methods
  48076. ValueCondition.prototype.isValid = function () {
  48077. switch (this.operator) {
  48078. case ValueCondition.IsGreater:
  48079. return this._effectiveTarget[this._property] > this.value;
  48080. case ValueCondition.IsLesser:
  48081. return this._effectiveTarget[this._property] < this.value;
  48082. case ValueCondition.IsEqual:
  48083. case ValueCondition.IsDifferent:
  48084. var check;
  48085. if (this.value.equals) {
  48086. check = this.value.equals(this._effectiveTarget[this._property]);
  48087. }
  48088. else {
  48089. check = this.value === this._effectiveTarget[this._property];
  48090. }
  48091. return this.operator === ValueCondition.IsEqual ? check : !check;
  48092. }
  48093. return false;
  48094. };
  48095. ValueCondition.prototype.serialize = function () {
  48096. return this._serialize({
  48097. name: "ValueCondition",
  48098. properties: [
  48099. BABYLON.Action._GetTargetProperty(this._target),
  48100. { name: "propertyPath", value: this.propertyPath },
  48101. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48102. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48103. ]
  48104. });
  48105. };
  48106. ValueCondition.GetOperatorName = function (operator) {
  48107. switch (operator) {
  48108. case ValueCondition._IsEqual: return "IsEqual";
  48109. case ValueCondition._IsDifferent: return "IsDifferent";
  48110. case ValueCondition._IsGreater: return "IsGreater";
  48111. case ValueCondition._IsLesser: return "IsLesser";
  48112. default: return "";
  48113. }
  48114. };
  48115. // Statics
  48116. ValueCondition._IsEqual = 0;
  48117. ValueCondition._IsDifferent = 1;
  48118. ValueCondition._IsGreater = 2;
  48119. ValueCondition._IsLesser = 3;
  48120. return ValueCondition;
  48121. }(Condition));
  48122. BABYLON.ValueCondition = ValueCondition;
  48123. var PredicateCondition = /** @class */ (function (_super) {
  48124. __extends(PredicateCondition, _super);
  48125. function PredicateCondition(actionManager, predicate) {
  48126. var _this = _super.call(this, actionManager) || this;
  48127. _this.predicate = predicate;
  48128. return _this;
  48129. }
  48130. PredicateCondition.prototype.isValid = function () {
  48131. return this.predicate();
  48132. };
  48133. return PredicateCondition;
  48134. }(Condition));
  48135. BABYLON.PredicateCondition = PredicateCondition;
  48136. var StateCondition = /** @class */ (function (_super) {
  48137. __extends(StateCondition, _super);
  48138. function StateCondition(actionManager, target, value) {
  48139. var _this = _super.call(this, actionManager) || this;
  48140. _this.value = value;
  48141. _this._target = target;
  48142. return _this;
  48143. }
  48144. // Methods
  48145. StateCondition.prototype.isValid = function () {
  48146. return this._target.state === this.value;
  48147. };
  48148. StateCondition.prototype.serialize = function () {
  48149. return this._serialize({
  48150. name: "StateCondition",
  48151. properties: [
  48152. BABYLON.Action._GetTargetProperty(this._target),
  48153. { name: "value", value: this.value }
  48154. ]
  48155. });
  48156. };
  48157. return StateCondition;
  48158. }(Condition));
  48159. BABYLON.StateCondition = StateCondition;
  48160. })(BABYLON || (BABYLON = {}));
  48161. //# sourceMappingURL=babylon.condition.js.map
  48162. var BABYLON;
  48163. (function (BABYLON) {
  48164. var Action = /** @class */ (function () {
  48165. function Action(triggerOptions, condition) {
  48166. this.triggerOptions = triggerOptions;
  48167. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48168. if (triggerOptions.parameter) {
  48169. this.trigger = triggerOptions.trigger;
  48170. this._triggerParameter = triggerOptions.parameter;
  48171. }
  48172. else {
  48173. this.trigger = triggerOptions;
  48174. }
  48175. this._nextActiveAction = this;
  48176. this._condition = condition;
  48177. }
  48178. // Methods
  48179. Action.prototype._prepare = function () {
  48180. };
  48181. Action.prototype.getTriggerParameter = function () {
  48182. return this._triggerParameter;
  48183. };
  48184. Action.prototype._executeCurrent = function (evt) {
  48185. if (this._nextActiveAction._condition) {
  48186. var condition = this._nextActiveAction._condition;
  48187. var currentRenderId = this._actionManager.getScene().getRenderId();
  48188. // We cache the current evaluation for the current frame
  48189. if (condition._evaluationId === currentRenderId) {
  48190. if (!condition._currentResult) {
  48191. return;
  48192. }
  48193. }
  48194. else {
  48195. condition._evaluationId = currentRenderId;
  48196. if (!condition.isValid()) {
  48197. condition._currentResult = false;
  48198. return;
  48199. }
  48200. condition._currentResult = true;
  48201. }
  48202. }
  48203. this.onBeforeExecuteObservable.notifyObservers(this);
  48204. this._nextActiveAction.execute(evt);
  48205. this.skipToNextActiveAction();
  48206. };
  48207. Action.prototype.execute = function (evt) {
  48208. };
  48209. Action.prototype.skipToNextActiveAction = function () {
  48210. if (this._nextActiveAction._child) {
  48211. if (!this._nextActiveAction._child._actionManager) {
  48212. this._nextActiveAction._child._actionManager = this._actionManager;
  48213. }
  48214. this._nextActiveAction = this._nextActiveAction._child;
  48215. }
  48216. else {
  48217. this._nextActiveAction = this;
  48218. }
  48219. };
  48220. Action.prototype.then = function (action) {
  48221. this._child = action;
  48222. action._actionManager = this._actionManager;
  48223. action._prepare();
  48224. return action;
  48225. };
  48226. Action.prototype._getProperty = function (propertyPath) {
  48227. return this._actionManager._getProperty(propertyPath);
  48228. };
  48229. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48230. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48231. };
  48232. Action.prototype.serialize = function (parent) {
  48233. };
  48234. // Called by BABYLON.Action objects in serialize(...). Internal use
  48235. Action.prototype._serialize = function (serializedAction, parent) {
  48236. var serializationObject = {
  48237. type: 1,
  48238. children: [],
  48239. name: serializedAction.name,
  48240. properties: serializedAction.properties || []
  48241. };
  48242. // Serialize child
  48243. if (this._child) {
  48244. this._child.serialize(serializationObject);
  48245. }
  48246. // Check if "this" has a condition
  48247. if (this._condition) {
  48248. var serializedCondition = this._condition.serialize();
  48249. serializedCondition.children.push(serializationObject);
  48250. if (parent) {
  48251. parent.children.push(serializedCondition);
  48252. }
  48253. return serializedCondition;
  48254. }
  48255. if (parent) {
  48256. parent.children.push(serializationObject);
  48257. }
  48258. return serializationObject;
  48259. };
  48260. Action._SerializeValueAsString = function (value) {
  48261. if (typeof value === "number") {
  48262. return value.toString();
  48263. }
  48264. if (typeof value === "boolean") {
  48265. return value ? "true" : "false";
  48266. }
  48267. if (value instanceof BABYLON.Vector2) {
  48268. return value.x + ", " + value.y;
  48269. }
  48270. if (value instanceof BABYLON.Vector3) {
  48271. return value.x + ", " + value.y + ", " + value.z;
  48272. }
  48273. if (value instanceof BABYLON.Color3) {
  48274. return value.r + ", " + value.g + ", " + value.b;
  48275. }
  48276. if (value instanceof BABYLON.Color4) {
  48277. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48278. }
  48279. return value; // string
  48280. };
  48281. Action._GetTargetProperty = function (target) {
  48282. return {
  48283. name: "target",
  48284. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48285. : target instanceof BABYLON.Light ? "LightProperties"
  48286. : target instanceof BABYLON.Camera ? "CameraProperties"
  48287. : "SceneProperties",
  48288. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48289. };
  48290. };
  48291. return Action;
  48292. }());
  48293. BABYLON.Action = Action;
  48294. })(BABYLON || (BABYLON = {}));
  48295. //# sourceMappingURL=babylon.action.js.map
  48296. var BABYLON;
  48297. (function (BABYLON) {
  48298. /**
  48299. * ActionEvent is the event beint sent when an action is triggered.
  48300. */
  48301. var ActionEvent = /** @class */ (function () {
  48302. /**
  48303. * @param source The mesh or sprite that triggered the action.
  48304. * @param pointerX The X mouse cursor position at the time of the event
  48305. * @param pointerY The Y mouse cursor position at the time of the event
  48306. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48307. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48308. */
  48309. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48310. this.source = source;
  48311. this.pointerX = pointerX;
  48312. this.pointerY = pointerY;
  48313. this.meshUnderPointer = meshUnderPointer;
  48314. this.sourceEvent = sourceEvent;
  48315. this.additionalData = additionalData;
  48316. }
  48317. /**
  48318. * Helper function to auto-create an ActionEvent from a source mesh.
  48319. * @param source The source mesh that triggered the event
  48320. * @param evt {Event} The original (browser) event
  48321. */
  48322. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48323. var scene = source.getScene();
  48324. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48325. };
  48326. /**
  48327. * Helper function to auto-create an ActionEvent from a source mesh.
  48328. * @param source The source sprite that triggered the event
  48329. * @param scene Scene associated with the sprite
  48330. * @param evt {Event} The original (browser) event
  48331. */
  48332. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48333. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48334. };
  48335. /**
  48336. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48337. * @param scene the scene where the event occurred
  48338. * @param evt {Event} The original (browser) event
  48339. */
  48340. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48341. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48342. };
  48343. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48344. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48345. };
  48346. return ActionEvent;
  48347. }());
  48348. BABYLON.ActionEvent = ActionEvent;
  48349. /**
  48350. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48351. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48352. */
  48353. var ActionManager = /** @class */ (function () {
  48354. function ActionManager(scene) {
  48355. // Members
  48356. this.actions = new Array();
  48357. this.hoverCursor = '';
  48358. this._scene = scene;
  48359. scene._actionManagers.push(this);
  48360. }
  48361. Object.defineProperty(ActionManager, "NothingTrigger", {
  48362. get: function () {
  48363. return ActionManager._NothingTrigger;
  48364. },
  48365. enumerable: true,
  48366. configurable: true
  48367. });
  48368. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48369. get: function () {
  48370. return ActionManager._OnPickTrigger;
  48371. },
  48372. enumerable: true,
  48373. configurable: true
  48374. });
  48375. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48376. get: function () {
  48377. return ActionManager._OnLeftPickTrigger;
  48378. },
  48379. enumerable: true,
  48380. configurable: true
  48381. });
  48382. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48383. get: function () {
  48384. return ActionManager._OnRightPickTrigger;
  48385. },
  48386. enumerable: true,
  48387. configurable: true
  48388. });
  48389. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48390. get: function () {
  48391. return ActionManager._OnCenterPickTrigger;
  48392. },
  48393. enumerable: true,
  48394. configurable: true
  48395. });
  48396. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48397. get: function () {
  48398. return ActionManager._OnPickDownTrigger;
  48399. },
  48400. enumerable: true,
  48401. configurable: true
  48402. });
  48403. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48404. get: function () {
  48405. return ActionManager._OnDoublePickTrigger;
  48406. },
  48407. enumerable: true,
  48408. configurable: true
  48409. });
  48410. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48411. get: function () {
  48412. return ActionManager._OnPickUpTrigger;
  48413. },
  48414. enumerable: true,
  48415. configurable: true
  48416. });
  48417. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48418. /// This trigger will only be raised if you also declared a OnPickDown
  48419. get: function () {
  48420. return ActionManager._OnPickOutTrigger;
  48421. },
  48422. enumerable: true,
  48423. configurable: true
  48424. });
  48425. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48426. get: function () {
  48427. return ActionManager._OnLongPressTrigger;
  48428. },
  48429. enumerable: true,
  48430. configurable: true
  48431. });
  48432. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48433. get: function () {
  48434. return ActionManager._OnPointerOverTrigger;
  48435. },
  48436. enumerable: true,
  48437. configurable: true
  48438. });
  48439. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48440. get: function () {
  48441. return ActionManager._OnPointerOutTrigger;
  48442. },
  48443. enumerable: true,
  48444. configurable: true
  48445. });
  48446. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48447. get: function () {
  48448. return ActionManager._OnEveryFrameTrigger;
  48449. },
  48450. enumerable: true,
  48451. configurable: true
  48452. });
  48453. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48454. get: function () {
  48455. return ActionManager._OnIntersectionEnterTrigger;
  48456. },
  48457. enumerable: true,
  48458. configurable: true
  48459. });
  48460. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48461. get: function () {
  48462. return ActionManager._OnIntersectionExitTrigger;
  48463. },
  48464. enumerable: true,
  48465. configurable: true
  48466. });
  48467. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48468. get: function () {
  48469. return ActionManager._OnKeyDownTrigger;
  48470. },
  48471. enumerable: true,
  48472. configurable: true
  48473. });
  48474. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48475. get: function () {
  48476. return ActionManager._OnKeyUpTrigger;
  48477. },
  48478. enumerable: true,
  48479. configurable: true
  48480. });
  48481. // Methods
  48482. ActionManager.prototype.dispose = function () {
  48483. var index = this._scene._actionManagers.indexOf(this);
  48484. for (var i = 0; i < this.actions.length; i++) {
  48485. var action = this.actions[i];
  48486. ActionManager.Triggers[action.trigger]--;
  48487. if (ActionManager.Triggers[action.trigger] === 0) {
  48488. delete ActionManager.Triggers[action.trigger];
  48489. }
  48490. }
  48491. if (index > -1) {
  48492. this._scene._actionManagers.splice(index, 1);
  48493. }
  48494. };
  48495. ActionManager.prototype.getScene = function () {
  48496. return this._scene;
  48497. };
  48498. /**
  48499. * Does this action manager handles actions of any of the given triggers
  48500. * @param {number[]} triggers - the triggers to be tested
  48501. * @return {boolean} whether one (or more) of the triggers is handeled
  48502. */
  48503. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48504. for (var index = 0; index < this.actions.length; index++) {
  48505. var action = this.actions[index];
  48506. if (triggers.indexOf(action.trigger) > -1) {
  48507. return true;
  48508. }
  48509. }
  48510. return false;
  48511. };
  48512. /**
  48513. * Does this action manager handles actions of a given trigger
  48514. * @param {number} trigger - the trigger to be tested
  48515. * @return {boolean} whether the trigger is handeled
  48516. */
  48517. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48518. for (var index = 0; index < this.actions.length; index++) {
  48519. var action = this.actions[index];
  48520. if (action.trigger === trigger) {
  48521. return true;
  48522. }
  48523. }
  48524. return false;
  48525. };
  48526. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48527. /**
  48528. * Does this action manager has pointer triggers
  48529. * @return {boolean} whether or not it has pointer triggers
  48530. */
  48531. get: function () {
  48532. for (var index = 0; index < this.actions.length; index++) {
  48533. var action = this.actions[index];
  48534. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48535. return true;
  48536. }
  48537. }
  48538. return false;
  48539. },
  48540. enumerable: true,
  48541. configurable: true
  48542. });
  48543. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48544. /**
  48545. * Does this action manager has pick triggers
  48546. * @return {boolean} whether or not it has pick triggers
  48547. */
  48548. get: function () {
  48549. for (var index = 0; index < this.actions.length; index++) {
  48550. var action = this.actions[index];
  48551. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48552. return true;
  48553. }
  48554. }
  48555. return false;
  48556. },
  48557. enumerable: true,
  48558. configurable: true
  48559. });
  48560. Object.defineProperty(ActionManager, "HasTriggers", {
  48561. /**
  48562. * Does exist one action manager with at least one trigger
  48563. * @return {boolean} whether or not it exists one action manager with one trigger
  48564. **/
  48565. get: function () {
  48566. for (var t in ActionManager.Triggers) {
  48567. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48568. return true;
  48569. }
  48570. }
  48571. return false;
  48572. },
  48573. enumerable: true,
  48574. configurable: true
  48575. });
  48576. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48577. /**
  48578. * Does exist one action manager with at least one pick trigger
  48579. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48580. **/
  48581. get: function () {
  48582. for (var t in ActionManager.Triggers) {
  48583. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48584. var t_int = parseInt(t);
  48585. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48586. return true;
  48587. }
  48588. }
  48589. }
  48590. return false;
  48591. },
  48592. enumerable: true,
  48593. configurable: true
  48594. });
  48595. /**
  48596. * Does exist one action manager that handles actions of a given trigger
  48597. * @param {number} trigger - the trigger to be tested
  48598. * @return {boolean} whether the trigger is handeled by at least one action manager
  48599. **/
  48600. ActionManager.HasSpecificTrigger = function (trigger) {
  48601. for (var t in ActionManager.Triggers) {
  48602. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48603. var t_int = parseInt(t);
  48604. if (t_int === trigger) {
  48605. return true;
  48606. }
  48607. }
  48608. }
  48609. return false;
  48610. };
  48611. /**
  48612. * Registers an action to this action manager
  48613. * @param {BABYLON.Action} action - the action to be registered
  48614. * @return {BABYLON.Action} the action amended (prepared) after registration
  48615. */
  48616. ActionManager.prototype.registerAction = function (action) {
  48617. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48618. if (this.getScene().actionManager !== this) {
  48619. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48620. return null;
  48621. }
  48622. }
  48623. this.actions.push(action);
  48624. if (ActionManager.Triggers[action.trigger]) {
  48625. ActionManager.Triggers[action.trigger]++;
  48626. }
  48627. else {
  48628. ActionManager.Triggers[action.trigger] = 1;
  48629. }
  48630. action._actionManager = this;
  48631. action._prepare();
  48632. return action;
  48633. };
  48634. /**
  48635. * Unregisters an action to this action manager
  48636. * @param action The action to be unregistered
  48637. * @return whether the action has been unregistered
  48638. */
  48639. ActionManager.prototype.unregisterAction = function (action) {
  48640. var index = this.actions.indexOf(action);
  48641. if (index !== -1) {
  48642. this.actions.splice(index, 1);
  48643. ActionManager.Triggers[action.trigger] -= 1;
  48644. if (ActionManager.Triggers[action.trigger] === 0) {
  48645. delete ActionManager.Triggers[action.trigger];
  48646. }
  48647. delete action._actionManager;
  48648. return true;
  48649. }
  48650. return false;
  48651. };
  48652. /**
  48653. * Process a specific trigger
  48654. * @param {number} trigger - the trigger to process
  48655. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48656. */
  48657. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48658. for (var index = 0; index < this.actions.length; index++) {
  48659. var action = this.actions[index];
  48660. if (action.trigger === trigger) {
  48661. if (evt) {
  48662. if (trigger === ActionManager.OnKeyUpTrigger
  48663. || trigger === ActionManager.OnKeyDownTrigger) {
  48664. var parameter = action.getTriggerParameter();
  48665. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48666. if (!parameter.toLowerCase) {
  48667. continue;
  48668. }
  48669. var lowerCase = parameter.toLowerCase();
  48670. if (lowerCase !== evt.sourceEvent.key) {
  48671. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48672. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48673. if (actualkey !== lowerCase) {
  48674. continue;
  48675. }
  48676. }
  48677. }
  48678. }
  48679. }
  48680. action._executeCurrent(evt);
  48681. }
  48682. }
  48683. };
  48684. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48685. var properties = propertyPath.split(".");
  48686. for (var index = 0; index < properties.length - 1; index++) {
  48687. target = target[properties[index]];
  48688. }
  48689. return target;
  48690. };
  48691. ActionManager.prototype._getProperty = function (propertyPath) {
  48692. var properties = propertyPath.split(".");
  48693. return properties[properties.length - 1];
  48694. };
  48695. ActionManager.prototype.serialize = function (name) {
  48696. var root = {
  48697. children: new Array(),
  48698. name: name,
  48699. type: 3,
  48700. properties: new Array() // Empty for root but required
  48701. };
  48702. for (var i = 0; i < this.actions.length; i++) {
  48703. var triggerObject = {
  48704. type: 0,
  48705. children: new Array(),
  48706. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48707. properties: new Array()
  48708. };
  48709. var triggerOptions = this.actions[i].triggerOptions;
  48710. if (triggerOptions && typeof triggerOptions !== "number") {
  48711. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48712. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48713. }
  48714. else {
  48715. var parameter = {};
  48716. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48717. if (triggerOptions.parameter.mesh) {
  48718. parameter._meshId = triggerOptions.parameter.mesh.id;
  48719. }
  48720. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48721. }
  48722. }
  48723. // Serialize child action, recursively
  48724. this.actions[i].serialize(triggerObject);
  48725. // Add serialized trigger
  48726. root.children.push(triggerObject);
  48727. }
  48728. return root;
  48729. };
  48730. ActionManager.Parse = function (parsedActions, object, scene) {
  48731. var actionManager = new ActionManager(scene);
  48732. if (object === null)
  48733. scene.actionManager = actionManager;
  48734. else
  48735. object.actionManager = actionManager;
  48736. // instanciate a new object
  48737. var instanciate = function (name, params) {
  48738. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48739. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48740. newInstance.constructor.apply(newInstance, params);
  48741. return newInstance;
  48742. };
  48743. var parseParameter = function (name, value, target, propertyPath) {
  48744. if (propertyPath === null) {
  48745. // String, boolean or float
  48746. var floatValue = parseFloat(value);
  48747. if (value === "true" || value === "false")
  48748. return value === "true";
  48749. else
  48750. return isNaN(floatValue) ? value : floatValue;
  48751. }
  48752. var effectiveTarget = propertyPath.split(".");
  48753. var values = value.split(",");
  48754. // Get effective Target
  48755. for (var i = 0; i < effectiveTarget.length; i++) {
  48756. target = target[effectiveTarget[i]];
  48757. }
  48758. // Return appropriate value with its type
  48759. if (typeof (target) === "boolean")
  48760. return values[0] === "true";
  48761. if (typeof (target) === "string")
  48762. return values[0];
  48763. // Parameters with multiple values such as Vector3 etc.
  48764. var split = new Array();
  48765. for (var i = 0; i < values.length; i++)
  48766. split.push(parseFloat(values[i]));
  48767. if (target instanceof BABYLON.Vector3)
  48768. return BABYLON.Vector3.FromArray(split);
  48769. if (target instanceof BABYLON.Vector4)
  48770. return BABYLON.Vector4.FromArray(split);
  48771. if (target instanceof BABYLON.Color3)
  48772. return BABYLON.Color3.FromArray(split);
  48773. if (target instanceof BABYLON.Color4)
  48774. return BABYLON.Color4.FromArray(split);
  48775. return parseFloat(values[0]);
  48776. };
  48777. // traverse graph per trigger
  48778. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48779. if (combineArray === void 0) { combineArray = null; }
  48780. if (parsedAction.detached)
  48781. return;
  48782. var parameters = new Array();
  48783. var target = null;
  48784. var propertyPath = null;
  48785. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48786. // Parameters
  48787. if (parsedAction.type === 2)
  48788. parameters.push(actionManager);
  48789. else
  48790. parameters.push(trigger);
  48791. if (combine) {
  48792. var actions = new Array();
  48793. for (var j = 0; j < parsedAction.combine.length; j++) {
  48794. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48795. }
  48796. parameters.push(actions);
  48797. }
  48798. else {
  48799. for (var i = 0; i < parsedAction.properties.length; i++) {
  48800. var value = parsedAction.properties[i].value;
  48801. var name = parsedAction.properties[i].name;
  48802. var targetType = parsedAction.properties[i].targetType;
  48803. if (name === "target")
  48804. if (targetType !== null && targetType === "SceneProperties")
  48805. value = target = scene;
  48806. else
  48807. value = target = scene.getNodeByName(value);
  48808. else if (name === "parent")
  48809. value = scene.getNodeByName(value);
  48810. else if (name === "sound")
  48811. value = scene.getSoundByName(value);
  48812. else if (name !== "propertyPath") {
  48813. if (parsedAction.type === 2 && name === "operator")
  48814. value = BABYLON.ValueCondition[value];
  48815. else
  48816. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48817. }
  48818. else {
  48819. propertyPath = value;
  48820. }
  48821. parameters.push(value);
  48822. }
  48823. }
  48824. if (combineArray === null) {
  48825. parameters.push(condition);
  48826. }
  48827. else {
  48828. parameters.push(null);
  48829. }
  48830. // If interpolate value action
  48831. if (parsedAction.name === "InterpolateValueAction") {
  48832. var param = parameters[parameters.length - 2];
  48833. parameters[parameters.length - 1] = param;
  48834. parameters[parameters.length - 2] = condition;
  48835. }
  48836. // Action or condition(s) and not CombineAction
  48837. var newAction = instanciate(parsedAction.name, parameters);
  48838. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48839. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48840. if (action)
  48841. action.then(nothing);
  48842. else
  48843. actionManager.registerAction(nothing);
  48844. action = nothing;
  48845. }
  48846. if (combineArray === null) {
  48847. if (newAction instanceof BABYLON.Condition) {
  48848. condition = newAction;
  48849. newAction = action;
  48850. }
  48851. else {
  48852. condition = null;
  48853. if (action)
  48854. action.then(newAction);
  48855. else
  48856. actionManager.registerAction(newAction);
  48857. }
  48858. }
  48859. else {
  48860. combineArray.push(newAction);
  48861. }
  48862. for (var i = 0; i < parsedAction.children.length; i++)
  48863. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48864. };
  48865. // triggers
  48866. for (var i = 0; i < parsedActions.children.length; i++) {
  48867. var triggerParams;
  48868. var trigger = parsedActions.children[i];
  48869. if (trigger.properties.length > 0) {
  48870. var param = trigger.properties[0].value;
  48871. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48872. if (value._meshId) {
  48873. value.mesh = scene.getMeshByID(value._meshId);
  48874. }
  48875. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48876. }
  48877. else
  48878. triggerParams = ActionManager[trigger.name];
  48879. for (var j = 0; j < trigger.children.length; j++) {
  48880. if (!trigger.detached)
  48881. traverse(trigger.children[j], triggerParams, null, null);
  48882. }
  48883. }
  48884. };
  48885. ActionManager.GetTriggerName = function (trigger) {
  48886. switch (trigger) {
  48887. case 0: return "NothingTrigger";
  48888. case 1: return "OnPickTrigger";
  48889. case 2: return "OnLeftPickTrigger";
  48890. case 3: return "OnRightPickTrigger";
  48891. case 4: return "OnCenterPickTrigger";
  48892. case 5: return "OnPickDownTrigger";
  48893. case 6: return "OnPickUpTrigger";
  48894. case 7: return "OnLongPressTrigger";
  48895. case 8: return "OnPointerOverTrigger";
  48896. case 9: return "OnPointerOutTrigger";
  48897. case 10: return "OnEveryFrameTrigger";
  48898. case 11: return "OnIntersectionEnterTrigger";
  48899. case 12: return "OnIntersectionExitTrigger";
  48900. case 13: return "OnKeyDownTrigger";
  48901. case 14: return "OnKeyUpTrigger";
  48902. case 15: return "OnPickOutTrigger";
  48903. default: return "";
  48904. }
  48905. };
  48906. // Statics
  48907. ActionManager._NothingTrigger = 0;
  48908. ActionManager._OnPickTrigger = 1;
  48909. ActionManager._OnLeftPickTrigger = 2;
  48910. ActionManager._OnRightPickTrigger = 3;
  48911. ActionManager._OnCenterPickTrigger = 4;
  48912. ActionManager._OnPickDownTrigger = 5;
  48913. ActionManager._OnDoublePickTrigger = 6;
  48914. ActionManager._OnPickUpTrigger = 7;
  48915. ActionManager._OnLongPressTrigger = 8;
  48916. ActionManager._OnPointerOverTrigger = 9;
  48917. ActionManager._OnPointerOutTrigger = 10;
  48918. ActionManager._OnEveryFrameTrigger = 11;
  48919. ActionManager._OnIntersectionEnterTrigger = 12;
  48920. ActionManager._OnIntersectionExitTrigger = 13;
  48921. ActionManager._OnKeyDownTrigger = 14;
  48922. ActionManager._OnKeyUpTrigger = 15;
  48923. ActionManager._OnPickOutTrigger = 16;
  48924. ActionManager.Triggers = {};
  48925. return ActionManager;
  48926. }());
  48927. BABYLON.ActionManager = ActionManager;
  48928. })(BABYLON || (BABYLON = {}));
  48929. //# sourceMappingURL=babylon.actionManager.js.map
  48930. var BABYLON;
  48931. (function (BABYLON) {
  48932. var InterpolateValueAction = /** @class */ (function (_super) {
  48933. __extends(InterpolateValueAction, _super);
  48934. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48935. if (duration === void 0) { duration = 1000; }
  48936. var _this = _super.call(this, triggerOptions, condition) || this;
  48937. _this.propertyPath = propertyPath;
  48938. _this.value = value;
  48939. _this.duration = duration;
  48940. _this.stopOtherAnimations = stopOtherAnimations;
  48941. _this.onInterpolationDone = onInterpolationDone;
  48942. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48943. _this._target = _this._effectiveTarget = target;
  48944. return _this;
  48945. }
  48946. InterpolateValueAction.prototype._prepare = function () {
  48947. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48948. this._property = this._getProperty(this.propertyPath);
  48949. };
  48950. InterpolateValueAction.prototype.execute = function () {
  48951. var _this = this;
  48952. var scene = this._actionManager.getScene();
  48953. var keys = [
  48954. {
  48955. frame: 0,
  48956. value: this._effectiveTarget[this._property]
  48957. }, {
  48958. frame: 100,
  48959. value: this.value
  48960. }
  48961. ];
  48962. var dataType;
  48963. if (typeof this.value === "number") {
  48964. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48965. }
  48966. else if (this.value instanceof BABYLON.Color3) {
  48967. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48968. }
  48969. else if (this.value instanceof BABYLON.Vector3) {
  48970. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48971. }
  48972. else if (this.value instanceof BABYLON.Matrix) {
  48973. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48974. }
  48975. else if (this.value instanceof BABYLON.Quaternion) {
  48976. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48977. }
  48978. else {
  48979. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48980. return;
  48981. }
  48982. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48983. animation.setKeys(keys);
  48984. if (this.stopOtherAnimations) {
  48985. scene.stopAnimation(this._effectiveTarget);
  48986. }
  48987. var wrapper = function () {
  48988. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48989. if (_this.onInterpolationDone) {
  48990. _this.onInterpolationDone();
  48991. }
  48992. };
  48993. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48994. };
  48995. InterpolateValueAction.prototype.serialize = function (parent) {
  48996. return _super.prototype._serialize.call(this, {
  48997. name: "InterpolateValueAction",
  48998. properties: [
  48999. BABYLON.Action._GetTargetProperty(this._target),
  49000. { name: "propertyPath", value: this.propertyPath },
  49001. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49002. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49003. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49004. ]
  49005. }, parent);
  49006. };
  49007. return InterpolateValueAction;
  49008. }(BABYLON.Action));
  49009. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49010. })(BABYLON || (BABYLON = {}));
  49011. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49012. var BABYLON;
  49013. (function (BABYLON) {
  49014. var SwitchBooleanAction = /** @class */ (function (_super) {
  49015. __extends(SwitchBooleanAction, _super);
  49016. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49017. var _this = _super.call(this, triggerOptions, condition) || this;
  49018. _this.propertyPath = propertyPath;
  49019. _this._target = _this._effectiveTarget = target;
  49020. return _this;
  49021. }
  49022. SwitchBooleanAction.prototype._prepare = function () {
  49023. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49024. this._property = this._getProperty(this.propertyPath);
  49025. };
  49026. SwitchBooleanAction.prototype.execute = function () {
  49027. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49028. };
  49029. SwitchBooleanAction.prototype.serialize = function (parent) {
  49030. return _super.prototype._serialize.call(this, {
  49031. name: "SwitchBooleanAction",
  49032. properties: [
  49033. BABYLON.Action._GetTargetProperty(this._target),
  49034. { name: "propertyPath", value: this.propertyPath }
  49035. ]
  49036. }, parent);
  49037. };
  49038. return SwitchBooleanAction;
  49039. }(BABYLON.Action));
  49040. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49041. var SetStateAction = /** @class */ (function (_super) {
  49042. __extends(SetStateAction, _super);
  49043. function SetStateAction(triggerOptions, target, value, condition) {
  49044. var _this = _super.call(this, triggerOptions, condition) || this;
  49045. _this.value = value;
  49046. _this._target = target;
  49047. return _this;
  49048. }
  49049. SetStateAction.prototype.execute = function () {
  49050. this._target.state = this.value;
  49051. };
  49052. SetStateAction.prototype.serialize = function (parent) {
  49053. return _super.prototype._serialize.call(this, {
  49054. name: "SetStateAction",
  49055. properties: [
  49056. BABYLON.Action._GetTargetProperty(this._target),
  49057. { name: "value", value: this.value }
  49058. ]
  49059. }, parent);
  49060. };
  49061. return SetStateAction;
  49062. }(BABYLON.Action));
  49063. BABYLON.SetStateAction = SetStateAction;
  49064. var SetValueAction = /** @class */ (function (_super) {
  49065. __extends(SetValueAction, _super);
  49066. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49067. var _this = _super.call(this, triggerOptions, condition) || this;
  49068. _this.propertyPath = propertyPath;
  49069. _this.value = value;
  49070. _this._target = _this._effectiveTarget = target;
  49071. return _this;
  49072. }
  49073. SetValueAction.prototype._prepare = function () {
  49074. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49075. this._property = this._getProperty(this.propertyPath);
  49076. };
  49077. SetValueAction.prototype.execute = function () {
  49078. this._effectiveTarget[this._property] = this.value;
  49079. if (this._target.markAsDirty) {
  49080. this._target.markAsDirty(this._property);
  49081. }
  49082. };
  49083. SetValueAction.prototype.serialize = function (parent) {
  49084. return _super.prototype._serialize.call(this, {
  49085. name: "SetValueAction",
  49086. properties: [
  49087. BABYLON.Action._GetTargetProperty(this._target),
  49088. { name: "propertyPath", value: this.propertyPath },
  49089. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49090. ]
  49091. }, parent);
  49092. };
  49093. return SetValueAction;
  49094. }(BABYLON.Action));
  49095. BABYLON.SetValueAction = SetValueAction;
  49096. var IncrementValueAction = /** @class */ (function (_super) {
  49097. __extends(IncrementValueAction, _super);
  49098. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49099. var _this = _super.call(this, triggerOptions, condition) || this;
  49100. _this.propertyPath = propertyPath;
  49101. _this.value = value;
  49102. _this._target = _this._effectiveTarget = target;
  49103. return _this;
  49104. }
  49105. IncrementValueAction.prototype._prepare = function () {
  49106. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49107. this._property = this._getProperty(this.propertyPath);
  49108. if (typeof this._effectiveTarget[this._property] !== "number") {
  49109. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49110. }
  49111. };
  49112. IncrementValueAction.prototype.execute = function () {
  49113. this._effectiveTarget[this._property] += this.value;
  49114. if (this._target.markAsDirty) {
  49115. this._target.markAsDirty(this._property);
  49116. }
  49117. };
  49118. IncrementValueAction.prototype.serialize = function (parent) {
  49119. return _super.prototype._serialize.call(this, {
  49120. name: "IncrementValueAction",
  49121. properties: [
  49122. BABYLON.Action._GetTargetProperty(this._target),
  49123. { name: "propertyPath", value: this.propertyPath },
  49124. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49125. ]
  49126. }, parent);
  49127. };
  49128. return IncrementValueAction;
  49129. }(BABYLON.Action));
  49130. BABYLON.IncrementValueAction = IncrementValueAction;
  49131. var PlayAnimationAction = /** @class */ (function (_super) {
  49132. __extends(PlayAnimationAction, _super);
  49133. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49134. var _this = _super.call(this, triggerOptions, condition) || this;
  49135. _this.from = from;
  49136. _this.to = to;
  49137. _this.loop = loop;
  49138. _this._target = target;
  49139. return _this;
  49140. }
  49141. PlayAnimationAction.prototype._prepare = function () {
  49142. };
  49143. PlayAnimationAction.prototype.execute = function () {
  49144. var scene = this._actionManager.getScene();
  49145. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49146. };
  49147. PlayAnimationAction.prototype.serialize = function (parent) {
  49148. return _super.prototype._serialize.call(this, {
  49149. name: "PlayAnimationAction",
  49150. properties: [
  49151. BABYLON.Action._GetTargetProperty(this._target),
  49152. { name: "from", value: String(this.from) },
  49153. { name: "to", value: String(this.to) },
  49154. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49155. ]
  49156. }, parent);
  49157. };
  49158. return PlayAnimationAction;
  49159. }(BABYLON.Action));
  49160. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49161. var StopAnimationAction = /** @class */ (function (_super) {
  49162. __extends(StopAnimationAction, _super);
  49163. function StopAnimationAction(triggerOptions, target, condition) {
  49164. var _this = _super.call(this, triggerOptions, condition) || this;
  49165. _this._target = target;
  49166. return _this;
  49167. }
  49168. StopAnimationAction.prototype._prepare = function () {
  49169. };
  49170. StopAnimationAction.prototype.execute = function () {
  49171. var scene = this._actionManager.getScene();
  49172. scene.stopAnimation(this._target);
  49173. };
  49174. StopAnimationAction.prototype.serialize = function (parent) {
  49175. return _super.prototype._serialize.call(this, {
  49176. name: "StopAnimationAction",
  49177. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49178. }, parent);
  49179. };
  49180. return StopAnimationAction;
  49181. }(BABYLON.Action));
  49182. BABYLON.StopAnimationAction = StopAnimationAction;
  49183. var DoNothingAction = /** @class */ (function (_super) {
  49184. __extends(DoNothingAction, _super);
  49185. function DoNothingAction(triggerOptions, condition) {
  49186. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49187. return _super.call(this, triggerOptions, condition) || this;
  49188. }
  49189. DoNothingAction.prototype.execute = function () {
  49190. };
  49191. DoNothingAction.prototype.serialize = function (parent) {
  49192. return _super.prototype._serialize.call(this, {
  49193. name: "DoNothingAction",
  49194. properties: []
  49195. }, parent);
  49196. };
  49197. return DoNothingAction;
  49198. }(BABYLON.Action));
  49199. BABYLON.DoNothingAction = DoNothingAction;
  49200. var CombineAction = /** @class */ (function (_super) {
  49201. __extends(CombineAction, _super);
  49202. function CombineAction(triggerOptions, children, condition) {
  49203. var _this = _super.call(this, triggerOptions, condition) || this;
  49204. _this.children = children;
  49205. return _this;
  49206. }
  49207. CombineAction.prototype._prepare = function () {
  49208. for (var index = 0; index < this.children.length; index++) {
  49209. this.children[index]._actionManager = this._actionManager;
  49210. this.children[index]._prepare();
  49211. }
  49212. };
  49213. CombineAction.prototype.execute = function (evt) {
  49214. for (var index = 0; index < this.children.length; index++) {
  49215. this.children[index].execute(evt);
  49216. }
  49217. };
  49218. CombineAction.prototype.serialize = function (parent) {
  49219. var serializationObject = _super.prototype._serialize.call(this, {
  49220. name: "CombineAction",
  49221. properties: [],
  49222. combine: []
  49223. }, parent);
  49224. for (var i = 0; i < this.children.length; i++) {
  49225. serializationObject.combine.push(this.children[i].serialize(null));
  49226. }
  49227. return serializationObject;
  49228. };
  49229. return CombineAction;
  49230. }(BABYLON.Action));
  49231. BABYLON.CombineAction = CombineAction;
  49232. var ExecuteCodeAction = /** @class */ (function (_super) {
  49233. __extends(ExecuteCodeAction, _super);
  49234. function ExecuteCodeAction(triggerOptions, func, condition) {
  49235. var _this = _super.call(this, triggerOptions, condition) || this;
  49236. _this.func = func;
  49237. return _this;
  49238. }
  49239. ExecuteCodeAction.prototype.execute = function (evt) {
  49240. this.func(evt);
  49241. };
  49242. return ExecuteCodeAction;
  49243. }(BABYLON.Action));
  49244. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49245. var SetParentAction = /** @class */ (function (_super) {
  49246. __extends(SetParentAction, _super);
  49247. function SetParentAction(triggerOptions, target, parent, condition) {
  49248. var _this = _super.call(this, triggerOptions, condition) || this;
  49249. _this._target = target;
  49250. _this._parent = parent;
  49251. return _this;
  49252. }
  49253. SetParentAction.prototype._prepare = function () {
  49254. };
  49255. SetParentAction.prototype.execute = function () {
  49256. if (this._target.parent === this._parent) {
  49257. return;
  49258. }
  49259. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49260. invertParentWorldMatrix.invert();
  49261. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49262. this._target.parent = this._parent;
  49263. };
  49264. SetParentAction.prototype.serialize = function (parent) {
  49265. return _super.prototype._serialize.call(this, {
  49266. name: "SetParentAction",
  49267. properties: [
  49268. BABYLON.Action._GetTargetProperty(this._target),
  49269. BABYLON.Action._GetTargetProperty(this._parent),
  49270. ]
  49271. }, parent);
  49272. };
  49273. return SetParentAction;
  49274. }(BABYLON.Action));
  49275. BABYLON.SetParentAction = SetParentAction;
  49276. var PlaySoundAction = /** @class */ (function (_super) {
  49277. __extends(PlaySoundAction, _super);
  49278. function PlaySoundAction(triggerOptions, sound, condition) {
  49279. var _this = _super.call(this, triggerOptions, condition) || this;
  49280. _this._sound = sound;
  49281. return _this;
  49282. }
  49283. PlaySoundAction.prototype._prepare = function () {
  49284. };
  49285. PlaySoundAction.prototype.execute = function () {
  49286. if (this._sound !== undefined)
  49287. this._sound.play();
  49288. };
  49289. PlaySoundAction.prototype.serialize = function (parent) {
  49290. return _super.prototype._serialize.call(this, {
  49291. name: "PlaySoundAction",
  49292. properties: [{ name: "sound", value: this._sound.name }]
  49293. }, parent);
  49294. };
  49295. return PlaySoundAction;
  49296. }(BABYLON.Action));
  49297. BABYLON.PlaySoundAction = PlaySoundAction;
  49298. var StopSoundAction = /** @class */ (function (_super) {
  49299. __extends(StopSoundAction, _super);
  49300. function StopSoundAction(triggerOptions, sound, condition) {
  49301. var _this = _super.call(this, triggerOptions, condition) || this;
  49302. _this._sound = sound;
  49303. return _this;
  49304. }
  49305. StopSoundAction.prototype._prepare = function () {
  49306. };
  49307. StopSoundAction.prototype.execute = function () {
  49308. if (this._sound !== undefined)
  49309. this._sound.stop();
  49310. };
  49311. StopSoundAction.prototype.serialize = function (parent) {
  49312. return _super.prototype._serialize.call(this, {
  49313. name: "StopSoundAction",
  49314. properties: [{ name: "sound", value: this._sound.name }]
  49315. }, parent);
  49316. };
  49317. return StopSoundAction;
  49318. }(BABYLON.Action));
  49319. BABYLON.StopSoundAction = StopSoundAction;
  49320. })(BABYLON || (BABYLON = {}));
  49321. //# sourceMappingURL=babylon.directActions.js.map
  49322. var BABYLON;
  49323. (function (BABYLON) {
  49324. var SpriteManager = /** @class */ (function () {
  49325. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49326. if (epsilon === void 0) { epsilon = 0.01; }
  49327. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49328. this.name = name;
  49329. this.sprites = new Array();
  49330. this.renderingGroupId = 0;
  49331. this.layerMask = 0x0FFFFFFF;
  49332. this.fogEnabled = true;
  49333. this.isPickable = false;
  49334. /**
  49335. * An event triggered when the manager is disposed.
  49336. * @type {BABYLON.Observable}
  49337. */
  49338. this.onDisposeObservable = new BABYLON.Observable();
  49339. this._vertexBuffers = {};
  49340. this._capacity = capacity;
  49341. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49342. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49343. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49344. if (cellSize.width && cellSize.height) {
  49345. this.cellWidth = cellSize.width;
  49346. this.cellHeight = cellSize.height;
  49347. }
  49348. else if (cellSize !== undefined) {
  49349. this.cellWidth = cellSize;
  49350. this.cellHeight = cellSize;
  49351. }
  49352. else {
  49353. return;
  49354. }
  49355. this._epsilon = epsilon;
  49356. this._scene = scene;
  49357. this._scene.spriteManagers.push(this);
  49358. var indices = [];
  49359. var index = 0;
  49360. for (var count = 0; count < capacity; count++) {
  49361. indices.push(index);
  49362. indices.push(index + 1);
  49363. indices.push(index + 2);
  49364. indices.push(index);
  49365. indices.push(index + 2);
  49366. indices.push(index + 3);
  49367. index += 4;
  49368. }
  49369. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49370. // VBO
  49371. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49372. this._vertexData = new Float32Array(capacity * 16 * 4);
  49373. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49374. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49375. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49376. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49377. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49378. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49379. this._vertexBuffers["options"] = options;
  49380. this._vertexBuffers["cellInfo"] = cellInfo;
  49381. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49382. // Effects
  49383. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49384. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49385. }
  49386. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49387. set: function (callback) {
  49388. if (this._onDisposeObserver) {
  49389. this.onDisposeObservable.remove(this._onDisposeObserver);
  49390. }
  49391. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49392. },
  49393. enumerable: true,
  49394. configurable: true
  49395. });
  49396. Object.defineProperty(SpriteManager.prototype, "texture", {
  49397. get: function () {
  49398. return this._spriteTexture;
  49399. },
  49400. set: function (value) {
  49401. this._spriteTexture = value;
  49402. },
  49403. enumerable: true,
  49404. configurable: true
  49405. });
  49406. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49407. var arrayOffset = index * 16;
  49408. if (offsetX === 0)
  49409. offsetX = this._epsilon;
  49410. else if (offsetX === 1)
  49411. offsetX = 1 - this._epsilon;
  49412. if (offsetY === 0)
  49413. offsetY = this._epsilon;
  49414. else if (offsetY === 1)
  49415. offsetY = 1 - this._epsilon;
  49416. this._vertexData[arrayOffset] = sprite.position.x;
  49417. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49418. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49419. this._vertexData[arrayOffset + 3] = sprite.angle;
  49420. this._vertexData[arrayOffset + 4] = sprite.width;
  49421. this._vertexData[arrayOffset + 5] = sprite.height;
  49422. this._vertexData[arrayOffset + 6] = offsetX;
  49423. this._vertexData[arrayOffset + 7] = offsetY;
  49424. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49425. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49426. var offset = (sprite.cellIndex / rowSize) >> 0;
  49427. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49428. this._vertexData[arrayOffset + 11] = offset;
  49429. // Color
  49430. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49431. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49432. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49433. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49434. };
  49435. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49436. var count = Math.min(this._capacity, this.sprites.length);
  49437. var min = BABYLON.Vector3.Zero();
  49438. var max = BABYLON.Vector3.Zero();
  49439. var distance = Number.MAX_VALUE;
  49440. var currentSprite = null;
  49441. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49442. var cameraView = camera.getViewMatrix();
  49443. for (var index = 0; index < count; index++) {
  49444. var sprite = this.sprites[index];
  49445. if (!sprite) {
  49446. continue;
  49447. }
  49448. if (predicate) {
  49449. if (!predicate(sprite)) {
  49450. continue;
  49451. }
  49452. }
  49453. else if (!sprite.isPickable) {
  49454. continue;
  49455. }
  49456. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49457. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49458. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49459. if (ray.intersectsBoxMinMax(min, max)) {
  49460. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49461. if (distance > currentDistance) {
  49462. distance = currentDistance;
  49463. currentSprite = sprite;
  49464. if (fastCheck) {
  49465. break;
  49466. }
  49467. }
  49468. }
  49469. }
  49470. if (currentSprite) {
  49471. var result = new BABYLON.PickingInfo();
  49472. result.hit = true;
  49473. result.pickedSprite = currentSprite;
  49474. result.distance = distance;
  49475. return result;
  49476. }
  49477. return null;
  49478. };
  49479. SpriteManager.prototype.render = function () {
  49480. // Check
  49481. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49482. return;
  49483. var engine = this._scene.getEngine();
  49484. var baseSize = this._spriteTexture.getBaseSize();
  49485. // Sprites
  49486. var deltaTime = engine.getDeltaTime();
  49487. var max = Math.min(this._capacity, this.sprites.length);
  49488. var rowSize = baseSize.width / this.cellWidth;
  49489. var offset = 0;
  49490. for (var index = 0; index < max; index++) {
  49491. var sprite = this.sprites[index];
  49492. if (!sprite) {
  49493. continue;
  49494. }
  49495. sprite._animate(deltaTime);
  49496. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49497. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49498. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49499. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49500. }
  49501. this._buffer.update(this._vertexData);
  49502. // Render
  49503. var effect = this._effectBase;
  49504. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49505. effect = this._effectFog;
  49506. }
  49507. engine.enableEffect(effect);
  49508. var viewMatrix = this._scene.getViewMatrix();
  49509. effect.setTexture("diffuseSampler", this._spriteTexture);
  49510. effect.setMatrix("view", viewMatrix);
  49511. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49512. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49513. // Fog
  49514. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49515. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49516. effect.setColor3("vFogColor", this._scene.fogColor);
  49517. }
  49518. // VBOs
  49519. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49520. // Draw order
  49521. engine.setDepthFunctionToLessOrEqual();
  49522. effect.setBool("alphaTest", true);
  49523. engine.setColorWrite(false);
  49524. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49525. engine.setColorWrite(true);
  49526. effect.setBool("alphaTest", false);
  49527. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49528. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49529. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49530. };
  49531. SpriteManager.prototype.dispose = function () {
  49532. if (this._buffer) {
  49533. this._buffer.dispose();
  49534. this._buffer = null;
  49535. }
  49536. if (this._indexBuffer) {
  49537. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49538. this._indexBuffer = null;
  49539. }
  49540. if (this._spriteTexture) {
  49541. this._spriteTexture.dispose();
  49542. this._spriteTexture = null;
  49543. }
  49544. // Remove from scene
  49545. var index = this._scene.spriteManagers.indexOf(this);
  49546. this._scene.spriteManagers.splice(index, 1);
  49547. // Callback
  49548. this.onDisposeObservable.notifyObservers(this);
  49549. this.onDisposeObservable.clear();
  49550. };
  49551. return SpriteManager;
  49552. }());
  49553. BABYLON.SpriteManager = SpriteManager;
  49554. })(BABYLON || (BABYLON = {}));
  49555. //# sourceMappingURL=babylon.spriteManager.js.map
  49556. var BABYLON;
  49557. (function (BABYLON) {
  49558. var Sprite = /** @class */ (function () {
  49559. function Sprite(name, manager) {
  49560. this.name = name;
  49561. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49562. this.width = 1.0;
  49563. this.height = 1.0;
  49564. this.angle = 0;
  49565. this.cellIndex = 0;
  49566. this.invertU = 0;
  49567. this.invertV = 0;
  49568. this.animations = new Array();
  49569. this.isPickable = false;
  49570. this._animationStarted = false;
  49571. this._loopAnimation = false;
  49572. this._fromIndex = 0;
  49573. this._toIndex = 0;
  49574. this._delay = 0;
  49575. this._direction = 1;
  49576. this._time = 0;
  49577. this._manager = manager;
  49578. this._manager.sprites.push(this);
  49579. this.position = BABYLON.Vector3.Zero();
  49580. }
  49581. Object.defineProperty(Sprite.prototype, "size", {
  49582. get: function () {
  49583. return this.width;
  49584. },
  49585. set: function (value) {
  49586. this.width = value;
  49587. this.height = value;
  49588. },
  49589. enumerable: true,
  49590. configurable: true
  49591. });
  49592. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49593. this._fromIndex = from;
  49594. this._toIndex = to;
  49595. this._loopAnimation = loop;
  49596. this._delay = delay;
  49597. this._animationStarted = true;
  49598. this._direction = from < to ? 1 : -1;
  49599. this.cellIndex = from;
  49600. this._time = 0;
  49601. this._onAnimationEnd = onAnimationEnd;
  49602. };
  49603. Sprite.prototype.stopAnimation = function () {
  49604. this._animationStarted = false;
  49605. };
  49606. Sprite.prototype._animate = function (deltaTime) {
  49607. if (!this._animationStarted)
  49608. return;
  49609. this._time += deltaTime;
  49610. if (this._time > this._delay) {
  49611. this._time = this._time % this._delay;
  49612. this.cellIndex += this._direction;
  49613. if (this.cellIndex > this._toIndex) {
  49614. if (this._loopAnimation) {
  49615. this.cellIndex = this._fromIndex;
  49616. }
  49617. else {
  49618. this.cellIndex = this._toIndex;
  49619. this._animationStarted = false;
  49620. if (this._onAnimationEnd) {
  49621. this._onAnimationEnd();
  49622. }
  49623. if (this.disposeWhenFinishedAnimating) {
  49624. this.dispose();
  49625. }
  49626. }
  49627. }
  49628. }
  49629. };
  49630. Sprite.prototype.dispose = function () {
  49631. for (var i = 0; i < this._manager.sprites.length; i++) {
  49632. if (this._manager.sprites[i] == this) {
  49633. this._manager.sprites.splice(i, 1);
  49634. }
  49635. }
  49636. };
  49637. return Sprite;
  49638. }());
  49639. BABYLON.Sprite = Sprite;
  49640. })(BABYLON || (BABYLON = {}));
  49641. //# sourceMappingURL=babylon.sprite.js.map
  49642. var BABYLON;
  49643. (function (BABYLON) {
  49644. var IntersectionInfo = /** @class */ (function () {
  49645. function IntersectionInfo(bu, bv, distance) {
  49646. this.bu = bu;
  49647. this.bv = bv;
  49648. this.distance = distance;
  49649. this.faceId = 0;
  49650. this.subMeshId = 0;
  49651. }
  49652. return IntersectionInfo;
  49653. }());
  49654. BABYLON.IntersectionInfo = IntersectionInfo;
  49655. var PickingInfo = /** @class */ (function () {
  49656. function PickingInfo() {
  49657. this.hit = false;
  49658. this.distance = 0;
  49659. this.pickedPoint = null;
  49660. this.pickedMesh = null;
  49661. this.bu = 0;
  49662. this.bv = 0;
  49663. this.faceId = -1;
  49664. this.subMeshId = 0;
  49665. this.pickedSprite = null;
  49666. }
  49667. // Methods
  49668. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49669. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49670. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49671. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49672. return null;
  49673. }
  49674. var indices = this.pickedMesh.getIndices();
  49675. if (!indices) {
  49676. return null;
  49677. }
  49678. var result;
  49679. if (useVerticesNormals) {
  49680. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49681. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49682. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49683. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49684. normal0 = normal0.scale(this.bu);
  49685. normal1 = normal1.scale(this.bv);
  49686. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49687. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49688. }
  49689. else {
  49690. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49691. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49692. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49693. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49694. var p1p2 = vertex1.subtract(vertex2);
  49695. var p3p2 = vertex3.subtract(vertex2);
  49696. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49697. }
  49698. if (useWorldCoordinates) {
  49699. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49700. }
  49701. return BABYLON.Vector3.Normalize(result);
  49702. };
  49703. PickingInfo.prototype.getTextureCoordinates = function () {
  49704. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49705. return null;
  49706. }
  49707. var indices = this.pickedMesh.getIndices();
  49708. if (!indices) {
  49709. return null;
  49710. }
  49711. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49712. if (!uvs) {
  49713. return null;
  49714. }
  49715. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49716. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49717. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49718. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49719. uv1 = uv1.scale(this.bu);
  49720. uv2 = uv2.scale(this.bv);
  49721. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49722. };
  49723. return PickingInfo;
  49724. }());
  49725. BABYLON.PickingInfo = PickingInfo;
  49726. })(BABYLON || (BABYLON = {}));
  49727. //# sourceMappingURL=babylon.pickingInfo.js.map
  49728. var BABYLON;
  49729. (function (BABYLON) {
  49730. var Ray = /** @class */ (function () {
  49731. function Ray(origin, direction, length) {
  49732. if (length === void 0) { length = Number.MAX_VALUE; }
  49733. this.origin = origin;
  49734. this.direction = direction;
  49735. this.length = length;
  49736. }
  49737. // Methods
  49738. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49739. var d = 0.0;
  49740. var maxValue = Number.MAX_VALUE;
  49741. var inv;
  49742. var min;
  49743. var max;
  49744. var temp;
  49745. if (Math.abs(this.direction.x) < 0.0000001) {
  49746. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49747. return false;
  49748. }
  49749. }
  49750. else {
  49751. inv = 1.0 / this.direction.x;
  49752. min = (minimum.x - this.origin.x) * inv;
  49753. max = (maximum.x - this.origin.x) * inv;
  49754. if (max === -Infinity) {
  49755. max = Infinity;
  49756. }
  49757. if (min > max) {
  49758. temp = min;
  49759. min = max;
  49760. max = temp;
  49761. }
  49762. d = Math.max(min, d);
  49763. maxValue = Math.min(max, maxValue);
  49764. if (d > maxValue) {
  49765. return false;
  49766. }
  49767. }
  49768. if (Math.abs(this.direction.y) < 0.0000001) {
  49769. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49770. return false;
  49771. }
  49772. }
  49773. else {
  49774. inv = 1.0 / this.direction.y;
  49775. min = (minimum.y - this.origin.y) * inv;
  49776. max = (maximum.y - this.origin.y) * inv;
  49777. if (max === -Infinity) {
  49778. max = Infinity;
  49779. }
  49780. if (min > max) {
  49781. temp = min;
  49782. min = max;
  49783. max = temp;
  49784. }
  49785. d = Math.max(min, d);
  49786. maxValue = Math.min(max, maxValue);
  49787. if (d > maxValue) {
  49788. return false;
  49789. }
  49790. }
  49791. if (Math.abs(this.direction.z) < 0.0000001) {
  49792. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49793. return false;
  49794. }
  49795. }
  49796. else {
  49797. inv = 1.0 / this.direction.z;
  49798. min = (minimum.z - this.origin.z) * inv;
  49799. max = (maximum.z - this.origin.z) * inv;
  49800. if (max === -Infinity) {
  49801. max = Infinity;
  49802. }
  49803. if (min > max) {
  49804. temp = min;
  49805. min = max;
  49806. max = temp;
  49807. }
  49808. d = Math.max(min, d);
  49809. maxValue = Math.min(max, maxValue);
  49810. if (d > maxValue) {
  49811. return false;
  49812. }
  49813. }
  49814. return true;
  49815. };
  49816. Ray.prototype.intersectsBox = function (box) {
  49817. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49818. };
  49819. Ray.prototype.intersectsSphere = function (sphere) {
  49820. var x = sphere.center.x - this.origin.x;
  49821. var y = sphere.center.y - this.origin.y;
  49822. var z = sphere.center.z - this.origin.z;
  49823. var pyth = (x * x) + (y * y) + (z * z);
  49824. var rr = sphere.radius * sphere.radius;
  49825. if (pyth <= rr) {
  49826. return true;
  49827. }
  49828. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49829. if (dot < 0.0) {
  49830. return false;
  49831. }
  49832. var temp = pyth - (dot * dot);
  49833. return temp <= rr;
  49834. };
  49835. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49836. if (!this._edge1) {
  49837. this._edge1 = BABYLON.Vector3.Zero();
  49838. this._edge2 = BABYLON.Vector3.Zero();
  49839. this._pvec = BABYLON.Vector3.Zero();
  49840. this._tvec = BABYLON.Vector3.Zero();
  49841. this._qvec = BABYLON.Vector3.Zero();
  49842. }
  49843. vertex1.subtractToRef(vertex0, this._edge1);
  49844. vertex2.subtractToRef(vertex0, this._edge2);
  49845. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49846. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49847. if (det === 0) {
  49848. return null;
  49849. }
  49850. var invdet = 1 / det;
  49851. this.origin.subtractToRef(vertex0, this._tvec);
  49852. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49853. if (bu < 0 || bu > 1.0) {
  49854. return null;
  49855. }
  49856. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49857. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49858. if (bv < 0 || bu + bv > 1.0) {
  49859. return null;
  49860. }
  49861. //check if the distance is longer than the predefined length.
  49862. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49863. if (distance > this.length) {
  49864. return null;
  49865. }
  49866. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49867. };
  49868. Ray.prototype.intersectsPlane = function (plane) {
  49869. var distance;
  49870. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49871. if (Math.abs(result1) < 9.99999997475243E-07) {
  49872. return null;
  49873. }
  49874. else {
  49875. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49876. distance = (-plane.d - result2) / result1;
  49877. if (distance < 0.0) {
  49878. if (distance < -9.99999997475243E-07) {
  49879. return null;
  49880. }
  49881. else {
  49882. return 0;
  49883. }
  49884. }
  49885. return distance;
  49886. }
  49887. };
  49888. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49889. var tm = BABYLON.Tmp.Matrix[0];
  49890. mesh.getWorldMatrix().invertToRef(tm);
  49891. if (this._tmpRay) {
  49892. Ray.TransformToRef(this, tm, this._tmpRay);
  49893. }
  49894. else {
  49895. this._tmpRay = Ray.Transform(this, tm);
  49896. }
  49897. return mesh.intersects(this._tmpRay, fastCheck);
  49898. };
  49899. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49900. if (results) {
  49901. results.length = 0;
  49902. }
  49903. else {
  49904. results = [];
  49905. }
  49906. for (var i = 0; i < meshes.length; i++) {
  49907. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49908. if (pickInfo.hit) {
  49909. results.push(pickInfo);
  49910. }
  49911. }
  49912. results.sort(this._comparePickingInfo);
  49913. return results;
  49914. };
  49915. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49916. if (pickingInfoA.distance < pickingInfoB.distance) {
  49917. return -1;
  49918. }
  49919. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49920. return 1;
  49921. }
  49922. else {
  49923. return 0;
  49924. }
  49925. };
  49926. /**
  49927. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49928. * @param sega the first point of the segment to test the intersection against
  49929. * @param segb the second point of the segment to test the intersection against
  49930. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49931. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49932. */
  49933. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49934. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49935. var u = segb.subtract(sega);
  49936. var v = rsegb.subtract(this.origin);
  49937. var w = sega.subtract(this.origin);
  49938. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49939. var b = BABYLON.Vector3.Dot(u, v);
  49940. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49941. var d = BABYLON.Vector3.Dot(u, w);
  49942. var e = BABYLON.Vector3.Dot(v, w);
  49943. var D = a * c - b * b; // always >= 0
  49944. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49945. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49946. // compute the line parameters of the two closest points
  49947. if (D < Ray.smallnum) {
  49948. sN = 0.0; // force using point P0 on segment S1
  49949. sD = 1.0; // to prevent possible division by 0.0 later
  49950. tN = e;
  49951. tD = c;
  49952. }
  49953. else {
  49954. sN = (b * e - c * d);
  49955. tN = (a * e - b * d);
  49956. if (sN < 0.0) {
  49957. sN = 0.0;
  49958. tN = e;
  49959. tD = c;
  49960. }
  49961. else if (sN > sD) {
  49962. sN = sD;
  49963. tN = e + b;
  49964. tD = c;
  49965. }
  49966. }
  49967. if (tN < 0.0) {
  49968. tN = 0.0;
  49969. // recompute sc for this edge
  49970. if (-d < 0.0) {
  49971. sN = 0.0;
  49972. }
  49973. else if (-d > a)
  49974. sN = sD;
  49975. else {
  49976. sN = -d;
  49977. sD = a;
  49978. }
  49979. }
  49980. else if (tN > tD) {
  49981. tN = tD;
  49982. // recompute sc for this edge
  49983. if ((-d + b) < 0.0) {
  49984. sN = 0;
  49985. }
  49986. else if ((-d + b) > a) {
  49987. sN = sD;
  49988. }
  49989. else {
  49990. sN = (-d + b);
  49991. sD = a;
  49992. }
  49993. }
  49994. // finally do the division to get sc and tc
  49995. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49996. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49997. // get the difference of the two closest points
  49998. var qtc = v.multiplyByFloats(tc, tc, tc);
  49999. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50000. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50001. if (isIntersected) {
  50002. return qtc.length();
  50003. }
  50004. return -1;
  50005. };
  50006. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50007. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50008. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50009. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50010. this.direction.normalize();
  50011. return this;
  50012. };
  50013. // Statics
  50014. Ray.Zero = function () {
  50015. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50016. };
  50017. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50018. var result = Ray.Zero();
  50019. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50020. };
  50021. /**
  50022. * 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
  50023. * transformed to the given world matrix.
  50024. * @param origin The origin point
  50025. * @param end The end point
  50026. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50027. */
  50028. Ray.CreateNewFromTo = function (origin, end, world) {
  50029. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50030. var direction = end.subtract(origin);
  50031. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50032. direction.normalize();
  50033. return Ray.Transform(new Ray(origin, direction, length), world);
  50034. };
  50035. Ray.Transform = function (ray, matrix) {
  50036. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50037. Ray.TransformToRef(ray, matrix, result);
  50038. return result;
  50039. };
  50040. Ray.TransformToRef = function (ray, matrix, result) {
  50041. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50042. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50043. result.length = ray.length;
  50044. var dir = result.direction;
  50045. var len = dir.length();
  50046. if (!(len === 0 || len === 1)) {
  50047. var num = 1.0 / len;
  50048. dir.x *= num;
  50049. dir.y *= num;
  50050. dir.z *= num;
  50051. result.length *= len;
  50052. }
  50053. };
  50054. Ray.smallnum = 0.00000001;
  50055. Ray.rayl = 10e8;
  50056. return Ray;
  50057. }());
  50058. BABYLON.Ray = Ray;
  50059. })(BABYLON || (BABYLON = {}));
  50060. //# sourceMappingURL=babylon.ray.js.map
  50061. var BABYLON;
  50062. (function (BABYLON) {
  50063. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50064. if (boxMin.x > sphereCenter.x + sphereRadius)
  50065. return false;
  50066. if (sphereCenter.x - sphereRadius > boxMax.x)
  50067. return false;
  50068. if (boxMin.y > sphereCenter.y + sphereRadius)
  50069. return false;
  50070. if (sphereCenter.y - sphereRadius > boxMax.y)
  50071. return false;
  50072. if (boxMin.z > sphereCenter.z + sphereRadius)
  50073. return false;
  50074. if (sphereCenter.z - sphereRadius > boxMax.z)
  50075. return false;
  50076. return true;
  50077. };
  50078. var getLowestRoot = (function () {
  50079. var result = { root: 0, found: false };
  50080. return function (a, b, c, maxR) {
  50081. result.root = 0;
  50082. result.found = false;
  50083. var determinant = b * b - 4.0 * a * c;
  50084. if (determinant < 0)
  50085. return result;
  50086. var sqrtD = Math.sqrt(determinant);
  50087. var r1 = (-b - sqrtD) / (2.0 * a);
  50088. var r2 = (-b + sqrtD) / (2.0 * a);
  50089. if (r1 > r2) {
  50090. var temp = r2;
  50091. r2 = r1;
  50092. r1 = temp;
  50093. }
  50094. if (r1 > 0 && r1 < maxR) {
  50095. result.root = r1;
  50096. result.found = true;
  50097. return result;
  50098. }
  50099. if (r2 > 0 && r2 < maxR) {
  50100. result.root = r2;
  50101. result.found = true;
  50102. return result;
  50103. }
  50104. return result;
  50105. };
  50106. })();
  50107. var Collider = /** @class */ (function () {
  50108. function Collider() {
  50109. this._collisionPoint = BABYLON.Vector3.Zero();
  50110. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50111. this._tempVector = BABYLON.Vector3.Zero();
  50112. this._tempVector2 = BABYLON.Vector3.Zero();
  50113. this._tempVector3 = BABYLON.Vector3.Zero();
  50114. this._tempVector4 = BABYLON.Vector3.Zero();
  50115. this._edge = BABYLON.Vector3.Zero();
  50116. this._baseToVertex = BABYLON.Vector3.Zero();
  50117. this._destinationPoint = BABYLON.Vector3.Zero();
  50118. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50119. this._displacementVector = BABYLON.Vector3.Zero();
  50120. this._radius = BABYLON.Vector3.One();
  50121. this._retry = 0;
  50122. this._basePointWorld = BABYLON.Vector3.Zero();
  50123. this._velocityWorld = BABYLON.Vector3.Zero();
  50124. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50125. this._collisionMask = -1;
  50126. }
  50127. Object.defineProperty(Collider.prototype, "collisionMask", {
  50128. get: function () {
  50129. return this._collisionMask;
  50130. },
  50131. set: function (mask) {
  50132. this._collisionMask = !isNaN(mask) ? mask : -1;
  50133. },
  50134. enumerable: true,
  50135. configurable: true
  50136. });
  50137. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50138. /**
  50139. * Gets the plane normal used to compute the sliding response (in local space)
  50140. */
  50141. get: function () {
  50142. return this._slidePlaneNormal;
  50143. },
  50144. enumerable: true,
  50145. configurable: true
  50146. });
  50147. // Methods
  50148. Collider.prototype._initialize = function (source, dir, e) {
  50149. this._velocity = dir;
  50150. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50151. this._basePoint = source;
  50152. source.multiplyToRef(this._radius, this._basePointWorld);
  50153. dir.multiplyToRef(this._radius, this._velocityWorld);
  50154. this._velocityWorldLength = this._velocityWorld.length();
  50155. this._epsilon = e;
  50156. this.collisionFound = false;
  50157. };
  50158. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50159. pa.subtractToRef(point, this._tempVector);
  50160. pb.subtractToRef(point, this._tempVector2);
  50161. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50162. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50163. if (d < 0)
  50164. return false;
  50165. pc.subtractToRef(point, this._tempVector3);
  50166. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50167. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50168. if (d < 0)
  50169. return false;
  50170. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50171. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50172. return d >= 0;
  50173. };
  50174. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50175. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50176. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50177. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50178. return false;
  50179. }
  50180. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50181. return false;
  50182. return true;
  50183. };
  50184. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50185. var t0;
  50186. var embeddedInPlane = false;
  50187. //defensive programming, actually not needed.
  50188. if (!trianglePlaneArray) {
  50189. trianglePlaneArray = [];
  50190. }
  50191. if (!trianglePlaneArray[faceIndex]) {
  50192. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50193. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50194. }
  50195. var trianglePlane = trianglePlaneArray[faceIndex];
  50196. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50197. return;
  50198. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50199. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50200. if (normalDotVelocity == 0) {
  50201. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50202. return;
  50203. embeddedInPlane = true;
  50204. t0 = 0;
  50205. }
  50206. else {
  50207. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50208. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50209. if (t0 > t1) {
  50210. var temp = t1;
  50211. t1 = t0;
  50212. t0 = temp;
  50213. }
  50214. if (t0 > 1.0 || t1 < 0.0)
  50215. return;
  50216. if (t0 < 0)
  50217. t0 = 0;
  50218. if (t0 > 1.0)
  50219. t0 = 1.0;
  50220. }
  50221. this._collisionPoint.copyFromFloats(0, 0, 0);
  50222. var found = false;
  50223. var t = 1.0;
  50224. if (!embeddedInPlane) {
  50225. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50226. this._velocity.scaleToRef(t0, this._tempVector);
  50227. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50228. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50229. found = true;
  50230. t = t0;
  50231. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50232. }
  50233. }
  50234. if (!found) {
  50235. var velocitySquaredLength = this._velocity.lengthSquared();
  50236. var a = velocitySquaredLength;
  50237. this._basePoint.subtractToRef(p1, this._tempVector);
  50238. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50239. var c = this._tempVector.lengthSquared() - 1.0;
  50240. var lowestRoot = getLowestRoot(a, b, c, t);
  50241. if (lowestRoot.found) {
  50242. t = lowestRoot.root;
  50243. found = true;
  50244. this._collisionPoint.copyFrom(p1);
  50245. }
  50246. this._basePoint.subtractToRef(p2, this._tempVector);
  50247. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50248. c = this._tempVector.lengthSquared() - 1.0;
  50249. lowestRoot = getLowestRoot(a, b, c, t);
  50250. if (lowestRoot.found) {
  50251. t = lowestRoot.root;
  50252. found = true;
  50253. this._collisionPoint.copyFrom(p2);
  50254. }
  50255. this._basePoint.subtractToRef(p3, this._tempVector);
  50256. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50257. c = this._tempVector.lengthSquared() - 1.0;
  50258. lowestRoot = getLowestRoot(a, b, c, t);
  50259. if (lowestRoot.found) {
  50260. t = lowestRoot.root;
  50261. found = true;
  50262. this._collisionPoint.copyFrom(p3);
  50263. }
  50264. p2.subtractToRef(p1, this._edge);
  50265. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50266. var edgeSquaredLength = this._edge.lengthSquared();
  50267. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50268. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50269. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50270. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50271. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50272. lowestRoot = getLowestRoot(a, b, c, t);
  50273. if (lowestRoot.found) {
  50274. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50275. if (f >= 0.0 && f <= 1.0) {
  50276. t = lowestRoot.root;
  50277. found = true;
  50278. this._edge.scaleInPlace(f);
  50279. p1.addToRef(this._edge, this._collisionPoint);
  50280. }
  50281. }
  50282. p3.subtractToRef(p2, this._edge);
  50283. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50284. edgeSquaredLength = this._edge.lengthSquared();
  50285. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50286. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50287. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50288. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50289. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50290. lowestRoot = getLowestRoot(a, b, c, t);
  50291. if (lowestRoot.found) {
  50292. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50293. if (f >= 0.0 && f <= 1.0) {
  50294. t = lowestRoot.root;
  50295. found = true;
  50296. this._edge.scaleInPlace(f);
  50297. p2.addToRef(this._edge, this._collisionPoint);
  50298. }
  50299. }
  50300. p1.subtractToRef(p3, this._edge);
  50301. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50302. edgeSquaredLength = this._edge.lengthSquared();
  50303. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50304. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50305. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50306. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50307. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50308. lowestRoot = getLowestRoot(a, b, c, t);
  50309. if (lowestRoot.found) {
  50310. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50311. if (f >= 0.0 && f <= 1.0) {
  50312. t = lowestRoot.root;
  50313. found = true;
  50314. this._edge.scaleInPlace(f);
  50315. p3.addToRef(this._edge, this._collisionPoint);
  50316. }
  50317. }
  50318. }
  50319. if (found) {
  50320. var distToCollision = t * this._velocity.length();
  50321. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50322. if (!this.intersectionPoint) {
  50323. this.intersectionPoint = this._collisionPoint.clone();
  50324. }
  50325. else {
  50326. this.intersectionPoint.copyFrom(this._collisionPoint);
  50327. }
  50328. this._nearestDistance = distToCollision;
  50329. this.collisionFound = true;
  50330. }
  50331. }
  50332. };
  50333. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50334. for (var i = indexStart; i < indexEnd; i += 3) {
  50335. var p1 = pts[indices[i] - decal];
  50336. var p2 = pts[indices[i + 1] - decal];
  50337. var p3 = pts[indices[i + 2] - decal];
  50338. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50339. }
  50340. };
  50341. Collider.prototype._getResponse = function (pos, vel) {
  50342. pos.addToRef(vel, this._destinationPoint);
  50343. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50344. this._basePoint.addToRef(vel, pos);
  50345. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50346. this._slidePlaneNormal.normalize();
  50347. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50348. pos.addInPlace(this._displacementVector);
  50349. this.intersectionPoint.addInPlace(this._displacementVector);
  50350. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50351. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50352. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50353. };
  50354. return Collider;
  50355. }());
  50356. BABYLON.Collider = Collider;
  50357. })(BABYLON || (BABYLON = {}));
  50358. //# sourceMappingURL=babylon.collider.js.map
  50359. var BABYLON;
  50360. (function (BABYLON) {
  50361. //WebWorker code will be inserted to this variable.
  50362. BABYLON.CollisionWorker = "";
  50363. var WorkerTaskType;
  50364. (function (WorkerTaskType) {
  50365. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50366. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50367. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50368. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50369. var WorkerReplyType;
  50370. (function (WorkerReplyType) {
  50371. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50372. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50373. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50374. var CollisionCoordinatorWorker = /** @class */ (function () {
  50375. function CollisionCoordinatorWorker() {
  50376. var _this = this;
  50377. this._scaledPosition = BABYLON.Vector3.Zero();
  50378. this._scaledVelocity = BABYLON.Vector3.Zero();
  50379. this.onMeshUpdated = function (transformNode) {
  50380. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50381. };
  50382. this.onGeometryUpdated = function (geometry) {
  50383. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50384. };
  50385. this._afterRender = function () {
  50386. if (!_this._init)
  50387. return;
  50388. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50389. return;
  50390. }
  50391. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50392. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50393. if (_this._runningUpdated > 4) {
  50394. return;
  50395. }
  50396. ++_this._runningUpdated;
  50397. var payload = {
  50398. updatedMeshes: _this._addUpdateMeshesList,
  50399. updatedGeometries: _this._addUpdateGeometriesList,
  50400. removedGeometries: _this._toRemoveGeometryArray,
  50401. removedMeshes: _this._toRemoveMeshesArray
  50402. };
  50403. var message = {
  50404. payload: payload,
  50405. taskType: WorkerTaskType.UPDATE
  50406. };
  50407. var serializable = [];
  50408. for (var id in payload.updatedGeometries) {
  50409. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50410. //prepare transferables
  50411. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50412. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50413. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50414. }
  50415. }
  50416. _this._worker.postMessage(message, serializable);
  50417. _this._addUpdateMeshesList = {};
  50418. _this._addUpdateGeometriesList = {};
  50419. _this._toRemoveGeometryArray = [];
  50420. _this._toRemoveMeshesArray = [];
  50421. };
  50422. this._onMessageFromWorker = function (e) {
  50423. var returnData = e.data;
  50424. if (returnData.error != WorkerReplyType.SUCCESS) {
  50425. //TODO what errors can be returned from the worker?
  50426. BABYLON.Tools.Warn("error returned from worker!");
  50427. return;
  50428. }
  50429. switch (returnData.taskType) {
  50430. case WorkerTaskType.INIT:
  50431. _this._init = true;
  50432. //Update the worked with ALL of the scene's current state
  50433. _this._scene.meshes.forEach(function (mesh) {
  50434. _this.onMeshAdded(mesh);
  50435. });
  50436. _this._scene.getGeometries().forEach(function (geometry) {
  50437. _this.onGeometryAdded(geometry);
  50438. });
  50439. break;
  50440. case WorkerTaskType.UPDATE:
  50441. _this._runningUpdated--;
  50442. break;
  50443. case WorkerTaskType.COLLIDE:
  50444. var returnPayload = returnData.payload;
  50445. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50446. return;
  50447. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50448. if (callback) {
  50449. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50450. if (mesh) {
  50451. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50452. }
  50453. }
  50454. //cleanup
  50455. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50456. break;
  50457. }
  50458. };
  50459. this._collisionsCallbackArray = [];
  50460. this._init = false;
  50461. this._runningUpdated = 0;
  50462. this._addUpdateMeshesList = {};
  50463. this._addUpdateGeometriesList = {};
  50464. this._toRemoveGeometryArray = [];
  50465. this._toRemoveMeshesArray = [];
  50466. }
  50467. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50468. if (!this._init)
  50469. return;
  50470. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50471. return;
  50472. position.divideToRef(collider._radius, this._scaledPosition);
  50473. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50474. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50475. var payload = {
  50476. collider: {
  50477. position: this._scaledPosition.asArray(),
  50478. velocity: this._scaledVelocity.asArray(),
  50479. radius: collider._radius.asArray()
  50480. },
  50481. collisionId: collisionIndex,
  50482. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50483. maximumRetry: maximumRetry
  50484. };
  50485. var message = {
  50486. payload: payload,
  50487. taskType: WorkerTaskType.COLLIDE
  50488. };
  50489. this._worker.postMessage(message);
  50490. };
  50491. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50492. this._scene = scene;
  50493. this._scene.registerAfterRender(this._afterRender);
  50494. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50495. this._worker = new Worker(workerUrl);
  50496. this._worker.onmessage = this._onMessageFromWorker;
  50497. var message = {
  50498. payload: {},
  50499. taskType: WorkerTaskType.INIT
  50500. };
  50501. this._worker.postMessage(message);
  50502. };
  50503. CollisionCoordinatorWorker.prototype.destroy = function () {
  50504. this._scene.unregisterAfterRender(this._afterRender);
  50505. this._worker.terminate();
  50506. };
  50507. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50508. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50509. this.onMeshUpdated(mesh);
  50510. };
  50511. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50512. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50513. };
  50514. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50515. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50516. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50517. this.onGeometryUpdated(geometry);
  50518. };
  50519. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50520. this._toRemoveGeometryArray.push(geometry.id);
  50521. };
  50522. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50523. var submeshes = [];
  50524. if (mesh.subMeshes) {
  50525. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50526. var boundingInfo = sm.getBoundingInfo();
  50527. return {
  50528. position: idx,
  50529. verticesStart: sm.verticesStart,
  50530. verticesCount: sm.verticesCount,
  50531. indexStart: sm.indexStart,
  50532. indexCount: sm.indexCount,
  50533. hasMaterial: !!sm.getMaterial(),
  50534. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50535. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50536. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50537. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50538. };
  50539. });
  50540. }
  50541. var geometryId = null;
  50542. if (mesh instanceof BABYLON.Mesh) {
  50543. var geometry = mesh.geometry;
  50544. geometryId = geometry ? geometry.id : null;
  50545. }
  50546. else if (mesh instanceof BABYLON.InstancedMesh) {
  50547. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50548. geometryId = geometry ? geometry.id : null;
  50549. }
  50550. var boundingInfo = mesh.getBoundingInfo();
  50551. return {
  50552. uniqueId: mesh.uniqueId,
  50553. id: mesh.id,
  50554. name: mesh.name,
  50555. geometryId: geometryId,
  50556. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50557. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50558. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50559. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50560. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50561. subMeshes: submeshes,
  50562. checkCollisions: mesh.checkCollisions
  50563. };
  50564. };
  50565. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50566. return {
  50567. id: geometry.id,
  50568. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50569. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50570. indices: new Uint32Array(geometry.getIndices() || []),
  50571. };
  50572. };
  50573. return CollisionCoordinatorWorker;
  50574. }());
  50575. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50576. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50577. function CollisionCoordinatorLegacy() {
  50578. this._scaledPosition = BABYLON.Vector3.Zero();
  50579. this._scaledVelocity = BABYLON.Vector3.Zero();
  50580. this._finalPosition = BABYLON.Vector3.Zero();
  50581. }
  50582. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50583. position.divideToRef(collider._radius, this._scaledPosition);
  50584. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50585. collider.collidedMesh = null;
  50586. collider._retry = 0;
  50587. collider._initialVelocity = this._scaledVelocity;
  50588. collider._initialPosition = this._scaledPosition;
  50589. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50590. this._finalPosition.multiplyInPlace(collider._radius);
  50591. //run the callback
  50592. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50593. };
  50594. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50595. this._scene = scene;
  50596. };
  50597. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50598. //Legacy need no destruction method.
  50599. };
  50600. //No update in legacy mode
  50601. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50602. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50603. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50604. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50605. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50606. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50607. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50608. if (excludedMesh === void 0) { excludedMesh = null; }
  50609. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50610. if (collider._retry >= maximumRetry) {
  50611. finalPosition.copyFrom(position);
  50612. return;
  50613. }
  50614. // Check if this is a mesh else camera or -1
  50615. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50616. collider._initialize(position, velocity, closeDistance);
  50617. // Check all meshes
  50618. for (var index = 0; index < this._scene.meshes.length; index++) {
  50619. var mesh = this._scene.meshes[index];
  50620. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50621. mesh._checkCollision(collider);
  50622. }
  50623. }
  50624. if (!collider.collisionFound) {
  50625. position.addToRef(velocity, finalPosition);
  50626. return;
  50627. }
  50628. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50629. collider._getResponse(position, velocity);
  50630. }
  50631. if (velocity.length() <= closeDistance) {
  50632. finalPosition.copyFrom(position);
  50633. return;
  50634. }
  50635. collider._retry++;
  50636. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50637. };
  50638. return CollisionCoordinatorLegacy;
  50639. }());
  50640. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50641. })(BABYLON || (BABYLON = {}));
  50642. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50643. var BABYLON;
  50644. (function (BABYLON) {
  50645. /**
  50646. * A particle represents one of the element emitted by a particle system.
  50647. * This is mainly define by its coordinates, direction, velocity and age.
  50648. */
  50649. var Particle = /** @class */ (function () {
  50650. /**
  50651. * Creates a new instance of @see Particle
  50652. * @param particleSystem the particle system the particle belongs to
  50653. */
  50654. function Particle(
  50655. /**
  50656. * particleSystem the particle system the particle belongs to.
  50657. */
  50658. particleSystem) {
  50659. this.particleSystem = particleSystem;
  50660. /**
  50661. * The world position of the particle in the scene.
  50662. */
  50663. this.position = BABYLON.Vector3.Zero();
  50664. /**
  50665. * The world direction of the particle in the scene.
  50666. */
  50667. this.direction = BABYLON.Vector3.Zero();
  50668. /**
  50669. * The color of the particle.
  50670. */
  50671. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50672. /**
  50673. * The color change of the particle per step.
  50674. */
  50675. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50676. /**
  50677. * Defines how long will the life of the particle be.
  50678. */
  50679. this.lifeTime = 1.0;
  50680. /**
  50681. * The current age of the particle.
  50682. */
  50683. this.age = 0;
  50684. /**
  50685. * The current size of the particle.
  50686. */
  50687. this.size = 0;
  50688. /**
  50689. * The current angle of the particle.
  50690. */
  50691. this.angle = 0;
  50692. /**
  50693. * Defines how fast is the angle changing.
  50694. */
  50695. this.angularSpeed = 0;
  50696. /**
  50697. * Defines the cell index used by the particle to be rendered from a sprite.
  50698. */
  50699. this.cellIndex = 0;
  50700. this._currentFrameCounter = 0;
  50701. if (!this.particleSystem.isAnimationSheetEnabled) {
  50702. return;
  50703. }
  50704. this.updateCellInfoFromSystem();
  50705. }
  50706. Particle.prototype.updateCellInfoFromSystem = function () {
  50707. this.cellIndex = this.particleSystem.startSpriteCellID;
  50708. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50709. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  50710. }
  50711. else {
  50712. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  50713. }
  50714. };
  50715. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50716. // (ageOffset / scaledUpdateSpeed) / available cells
  50717. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50718. this._currentFrameCounter += scaledUpdateSpeed;
  50719. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50720. this._currentFrameCounter = 0;
  50721. this.cellIndex++;
  50722. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50723. this.cellIndex = this.particleSystem.endSpriteCellID;
  50724. }
  50725. }
  50726. };
  50727. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  50728. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50729. this.cellIndex++;
  50730. this._currentFrameCounter = 0;
  50731. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50732. if (this.particleSystem.spriteCellLoop) {
  50733. this.cellIndex = this.particleSystem.startSpriteCellID;
  50734. }
  50735. else {
  50736. this.cellIndex = this.particleSystem.endSpriteCellID;
  50737. }
  50738. }
  50739. }
  50740. else {
  50741. this._currentFrameCounter++;
  50742. }
  50743. };
  50744. /**
  50745. * Copy the properties of particle to another one.
  50746. * @param other the particle to copy the information to.
  50747. */
  50748. Particle.prototype.copyTo = function (other) {
  50749. other.position.copyFrom(this.position);
  50750. other.direction.copyFrom(this.direction);
  50751. other.color.copyFrom(this.color);
  50752. other.colorStep.copyFrom(this.colorStep);
  50753. other.lifeTime = this.lifeTime;
  50754. other.age = this.age;
  50755. other.size = this.size;
  50756. other.angle = this.angle;
  50757. other.angularSpeed = this.angularSpeed;
  50758. other.particleSystem = this.particleSystem;
  50759. other.cellIndex = this.cellIndex;
  50760. };
  50761. return Particle;
  50762. }());
  50763. BABYLON.Particle = Particle;
  50764. })(BABYLON || (BABYLON = {}));
  50765. //# sourceMappingURL=babylon.particle.js.map
  50766. var BABYLON;
  50767. (function (BABYLON) {
  50768. /**
  50769. * This represents a particle system in Babylon.
  50770. * 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.
  50771. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50772. * @example https://doc.babylonjs.com/babylon101/particles
  50773. */
  50774. var ParticleSystem = /** @class */ (function () {
  50775. /**
  50776. * Instantiates a particle system.
  50777. * 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.
  50778. * @param name The name of the particle system
  50779. * @param capacity The max number of particles alive at the same time
  50780. * @param scene The scene the particle system belongs to
  50781. * @param customEffect a custom effect used to change the way particles are rendered by default
  50782. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50783. * @param epsilon Offset used to render the particles
  50784. */
  50785. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50786. if (customEffect === void 0) { customEffect = null; }
  50787. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50788. if (epsilon === void 0) { epsilon = 0.01; }
  50789. var _this = this;
  50790. /**
  50791. * List of animations used by the particle system.
  50792. */
  50793. this.animations = [];
  50794. /**
  50795. * The rendering group used by the Particle system to chose when to render.
  50796. */
  50797. this.renderingGroupId = 0;
  50798. /**
  50799. * The emitter represents the Mesh or position we are attaching the particle system to.
  50800. */
  50801. this.emitter = null;
  50802. /**
  50803. * The maximum number of particles to emit per frame
  50804. */
  50805. this.emitRate = 10;
  50806. /**
  50807. * If you want to launch only a few particles at once, that can be done, as well.
  50808. */
  50809. this.manualEmitCount = -1;
  50810. /**
  50811. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50812. */
  50813. this.updateSpeed = 0.01;
  50814. /**
  50815. * The amount of time the particle system is running (depends of the overall update speed).
  50816. */
  50817. this.targetStopDuration = 0;
  50818. /**
  50819. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50820. */
  50821. this.disposeOnStop = false;
  50822. /**
  50823. * Minimum power of emitting particles.
  50824. */
  50825. this.minEmitPower = 1;
  50826. /**
  50827. * Maximum power of emitting particles.
  50828. */
  50829. this.maxEmitPower = 1;
  50830. /**
  50831. * Minimum life time of emitting particles.
  50832. */
  50833. this.minLifeTime = 1;
  50834. /**
  50835. * Maximum life time of emitting particles.
  50836. */
  50837. this.maxLifeTime = 1;
  50838. /**
  50839. * Minimum Size of emitting particles.
  50840. */
  50841. this.minSize = 1;
  50842. /**
  50843. * Maximum Size of emitting particles.
  50844. */
  50845. this.maxSize = 1;
  50846. /**
  50847. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50848. */
  50849. this.minAngularSpeed = 0;
  50850. /**
  50851. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50852. */
  50853. this.maxAngularSpeed = 0;
  50854. /**
  50855. * The layer mask we are rendering the particles through.
  50856. */
  50857. this.layerMask = 0x0FFFFFFF;
  50858. /**
  50859. * This can help using your own shader to render the particle system.
  50860. * The according effect will be created
  50861. */
  50862. this.customShader = null;
  50863. /**
  50864. * By default particle system starts as soon as they are created. This prevents the
  50865. * automatic start to happen and let you decide when to start emitting particles.
  50866. */
  50867. this.preventAutoStart = false;
  50868. /**
  50869. * Callback triggered when the particle animation is ending.
  50870. */
  50871. this.onAnimationEnd = null;
  50872. /**
  50873. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50874. */
  50875. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50876. /**
  50877. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50878. * to override the particles.
  50879. */
  50880. this.forceDepthWrite = false;
  50881. /**
  50882. * You can use gravity if you want to give an orientation to your particles.
  50883. */
  50884. this.gravity = BABYLON.Vector3.Zero();
  50885. /**
  50886. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50887. */
  50888. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50889. /**
  50890. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50891. */
  50892. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50893. /**
  50894. * Color the particle will have at the end of its lifetime.
  50895. */
  50896. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50897. /**
  50898. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50899. */
  50900. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50901. /**
  50902. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50903. */
  50904. this.spriteCellLoop = true;
  50905. /**
  50906. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50907. */
  50908. this.spriteCellChangeSpeed = 0;
  50909. /**
  50910. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50911. */
  50912. this.startSpriteCellID = 0;
  50913. /**
  50914. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50915. */
  50916. this.endSpriteCellID = 0;
  50917. /**
  50918. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50919. */
  50920. this.spriteCellWidth = 0;
  50921. /**
  50922. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50923. */
  50924. this.spriteCellHeight = 0;
  50925. /**
  50926. * An event triggered when the system is disposed.
  50927. */
  50928. this.onDisposeObservable = new BABYLON.Observable();
  50929. this._particles = new Array();
  50930. this._stockParticles = new Array();
  50931. this._newPartsExcess = 0;
  50932. this._vertexBuffers = {};
  50933. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50934. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50935. this._scaledDirection = BABYLON.Vector3.Zero();
  50936. this._scaledGravity = BABYLON.Vector3.Zero();
  50937. this._currentRenderId = -1;
  50938. this._started = false;
  50939. this._stopped = false;
  50940. this._actualFrame = 0;
  50941. this._vertexBufferSize = 11;
  50942. // start of sub system methods
  50943. /**
  50944. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50945. * Its lifetime will start back at 0.
  50946. */
  50947. this.recycleParticle = function (particle) {
  50948. var lastParticle = _this._particles.pop();
  50949. if (lastParticle !== particle) {
  50950. lastParticle.copyTo(particle);
  50951. }
  50952. _this._stockParticles.push(lastParticle);
  50953. };
  50954. this._createParticle = function () {
  50955. var particle;
  50956. if (_this._stockParticles.length !== 0) {
  50957. particle = _this._stockParticles.pop();
  50958. particle.age = 0;
  50959. particle.cellIndex = _this.startSpriteCellID;
  50960. }
  50961. else {
  50962. particle = new BABYLON.Particle(_this);
  50963. }
  50964. return particle;
  50965. };
  50966. this._emitFromParticle = function (particle) {
  50967. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  50968. return;
  50969. }
  50970. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  50971. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  50972. subSystem._rootParticleSystem = _this;
  50973. _this.activeSubSystems.push(subSystem);
  50974. subSystem.start();
  50975. };
  50976. this._appendParticleVertexes = null;
  50977. this.id = name;
  50978. this.name = name;
  50979. this._capacity = capacity;
  50980. this._epsilon = epsilon;
  50981. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50982. if (isAnimationSheetEnabled) {
  50983. this._vertexBufferSize = 12;
  50984. }
  50985. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50986. this._customEffect = customEffect;
  50987. scene.particleSystems.push(this);
  50988. this._createIndexBuffer();
  50989. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50990. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50991. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50992. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50993. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50994. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50995. if (this._isAnimationSheetEnabled) {
  50996. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50997. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50998. }
  50999. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51000. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51001. this._vertexBuffers["options"] = options;
  51002. // Default emitter type
  51003. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51004. this.updateFunction = function (particles) {
  51005. for (var index = 0; index < particles.length; index++) {
  51006. var particle = particles[index];
  51007. particle.age += _this._scaledUpdateSpeed;
  51008. if (particle.age >= particle.lifeTime) {
  51009. _this._emitFromParticle(particle);
  51010. _this.recycleParticle(particle);
  51011. index--;
  51012. continue;
  51013. }
  51014. else {
  51015. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51016. particle.color.addInPlace(_this._scaledColorStep);
  51017. if (particle.color.a < 0)
  51018. particle.color.a = 0;
  51019. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51020. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51021. particle.position.addInPlace(_this._scaledDirection);
  51022. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51023. particle.direction.addInPlace(_this._scaledGravity);
  51024. if (_this._isAnimationSheetEnabled) {
  51025. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51026. }
  51027. }
  51028. }
  51029. };
  51030. }
  51031. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51032. /**
  51033. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51034. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51035. */
  51036. get: function () {
  51037. if (this.particleEmitterType.direction1) {
  51038. return this.particleEmitterType.direction1;
  51039. }
  51040. return BABYLON.Vector3.Zero();
  51041. },
  51042. set: function (value) {
  51043. if (this.particleEmitterType.direction1) {
  51044. this.particleEmitterType.direction1 = value;
  51045. }
  51046. },
  51047. enumerable: true,
  51048. configurable: true
  51049. });
  51050. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51051. /**
  51052. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51053. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51054. */
  51055. get: function () {
  51056. if (this.particleEmitterType.direction2) {
  51057. return this.particleEmitterType.direction2;
  51058. }
  51059. return BABYLON.Vector3.Zero();
  51060. },
  51061. set: function (value) {
  51062. if (this.particleEmitterType.direction2) {
  51063. this.particleEmitterType.direction2 = value;
  51064. }
  51065. },
  51066. enumerable: true,
  51067. configurable: true
  51068. });
  51069. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51070. /**
  51071. * 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.
  51072. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51073. */
  51074. get: function () {
  51075. if (this.particleEmitterType.minEmitBox) {
  51076. return this.particleEmitterType.minEmitBox;
  51077. }
  51078. return BABYLON.Vector3.Zero();
  51079. },
  51080. set: function (value) {
  51081. if (this.particleEmitterType.minEmitBox) {
  51082. this.particleEmitterType.minEmitBox = value;
  51083. }
  51084. },
  51085. enumerable: true,
  51086. configurable: true
  51087. });
  51088. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51089. /**
  51090. * 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.
  51091. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51092. */
  51093. get: function () {
  51094. if (this.particleEmitterType.maxEmitBox) {
  51095. return this.particleEmitterType.maxEmitBox;
  51096. }
  51097. return BABYLON.Vector3.Zero();
  51098. },
  51099. set: function (value) {
  51100. if (this.particleEmitterType.maxEmitBox) {
  51101. this.particleEmitterType.maxEmitBox = value;
  51102. }
  51103. },
  51104. enumerable: true,
  51105. configurable: true
  51106. });
  51107. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51108. /**
  51109. * Sets a callback that will be triggered when the system is disposed.
  51110. */
  51111. set: function (callback) {
  51112. if (this._onDisposeObserver) {
  51113. this.onDisposeObservable.remove(this._onDisposeObserver);
  51114. }
  51115. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51116. },
  51117. enumerable: true,
  51118. configurable: true
  51119. });
  51120. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51121. /**
  51122. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51123. */
  51124. get: function () {
  51125. return this._isAnimationSheetEnabled;
  51126. },
  51127. enumerable: true,
  51128. configurable: true
  51129. });
  51130. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51131. //end of Sub-emitter
  51132. /**
  51133. * Gets the current list of active particles
  51134. */
  51135. get: function () {
  51136. return this._particles;
  51137. },
  51138. enumerable: true,
  51139. configurable: true
  51140. });
  51141. /**
  51142. * Returns the string "ParticleSystem"
  51143. * @returns a string containing the class name
  51144. */
  51145. ParticleSystem.prototype.getClassName = function () {
  51146. return "ParticleSystem";
  51147. };
  51148. ParticleSystem.prototype._createIndexBuffer = function () {
  51149. var indices = [];
  51150. var index = 0;
  51151. for (var count = 0; count < this._capacity; count++) {
  51152. indices.push(index);
  51153. indices.push(index + 1);
  51154. indices.push(index + 2);
  51155. indices.push(index);
  51156. indices.push(index + 2);
  51157. indices.push(index + 3);
  51158. index += 4;
  51159. }
  51160. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51161. };
  51162. /**
  51163. * Gets the maximum number of particles active at the same time.
  51164. * @returns The max number of active particles.
  51165. */
  51166. ParticleSystem.prototype.getCapacity = function () {
  51167. return this._capacity;
  51168. };
  51169. /**
  51170. * Gets Wether there are still active particles in the system.
  51171. * @returns True if it is alive, otherwise false.
  51172. */
  51173. ParticleSystem.prototype.isAlive = function () {
  51174. return this._alive;
  51175. };
  51176. /**
  51177. * Gets Wether the system has been started.
  51178. * @returns True if it has been started, otherwise false.
  51179. */
  51180. ParticleSystem.prototype.isStarted = function () {
  51181. return this._started;
  51182. };
  51183. /**
  51184. * Starts the particle system and begins to emit.
  51185. */
  51186. ParticleSystem.prototype.start = function () {
  51187. this._started = true;
  51188. this._stopped = false;
  51189. this._actualFrame = 0;
  51190. if (this.subEmitters && this.subEmitters.length != 0) {
  51191. this.activeSubSystems = new Array();
  51192. }
  51193. };
  51194. /**
  51195. * Stops the particle system.
  51196. * @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.
  51197. */
  51198. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51199. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51200. this._stopped = true;
  51201. if (stopSubEmitters) {
  51202. this._stopSubEmitters();
  51203. }
  51204. };
  51205. // animation sheet
  51206. /**
  51207. * Remove all active particles
  51208. */
  51209. ParticleSystem.prototype.reset = function () {
  51210. this._stockParticles = [];
  51211. this._particles = [];
  51212. };
  51213. /**
  51214. * @ignore (for internal use only)
  51215. */
  51216. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51217. var offset = index * this._vertexBufferSize;
  51218. this._vertexData[offset] = particle.position.x;
  51219. this._vertexData[offset + 1] = particle.position.y;
  51220. this._vertexData[offset + 2] = particle.position.z;
  51221. this._vertexData[offset + 3] = particle.color.r;
  51222. this._vertexData[offset + 4] = particle.color.g;
  51223. this._vertexData[offset + 5] = particle.color.b;
  51224. this._vertexData[offset + 6] = particle.color.a;
  51225. this._vertexData[offset + 7] = particle.angle;
  51226. this._vertexData[offset + 8] = particle.size;
  51227. this._vertexData[offset + 9] = offsetX;
  51228. this._vertexData[offset + 10] = offsetY;
  51229. };
  51230. /**
  51231. * @ignore (for internal use only)
  51232. */
  51233. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51234. if (offsetX === 0)
  51235. offsetX = this._epsilon;
  51236. else if (offsetX === 1)
  51237. offsetX = 1 - this._epsilon;
  51238. if (offsetY === 0)
  51239. offsetY = this._epsilon;
  51240. else if (offsetY === 1)
  51241. offsetY = 1 - this._epsilon;
  51242. var offset = index * this._vertexBufferSize;
  51243. this._vertexData[offset] = particle.position.x;
  51244. this._vertexData[offset + 1] = particle.position.y;
  51245. this._vertexData[offset + 2] = particle.position.z;
  51246. this._vertexData[offset + 3] = particle.color.r;
  51247. this._vertexData[offset + 4] = particle.color.g;
  51248. this._vertexData[offset + 5] = particle.color.b;
  51249. this._vertexData[offset + 6] = particle.color.a;
  51250. this._vertexData[offset + 7] = particle.angle;
  51251. this._vertexData[offset + 8] = particle.size;
  51252. this._vertexData[offset + 9] = offsetX;
  51253. this._vertexData[offset + 10] = offsetY;
  51254. this._vertexData[offset + 11] = particle.cellIndex;
  51255. };
  51256. ParticleSystem.prototype._stopSubEmitters = function () {
  51257. if (!this.activeSubSystems) {
  51258. return;
  51259. }
  51260. this.activeSubSystems.forEach(function (subSystem) {
  51261. subSystem.stop(true);
  51262. });
  51263. this.activeSubSystems = new Array();
  51264. };
  51265. ParticleSystem.prototype._removeFromRoot = function () {
  51266. if (!this._rootParticleSystem) {
  51267. return;
  51268. }
  51269. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51270. if (index !== -1) {
  51271. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51272. }
  51273. };
  51274. // end of sub system methods
  51275. ParticleSystem.prototype._update = function (newParticles) {
  51276. // Update current
  51277. this._alive = this._particles.length > 0;
  51278. this.updateFunction(this._particles);
  51279. // Add new ones
  51280. var worldMatrix;
  51281. if (this.emitter.position) {
  51282. var emitterMesh = this.emitter;
  51283. worldMatrix = emitterMesh.getWorldMatrix();
  51284. }
  51285. else {
  51286. var emitterPosition = this.emitter;
  51287. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51288. }
  51289. var particle;
  51290. for (var index = 0; index < newParticles; index++) {
  51291. if (this._particles.length === this._capacity) {
  51292. break;
  51293. }
  51294. particle = this._createParticle();
  51295. this._particles.push(particle);
  51296. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51297. if (this.startPositionFunction) {
  51298. this.startPositionFunction(worldMatrix, particle.position, particle);
  51299. }
  51300. else {
  51301. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51302. }
  51303. if (this.startDirectionFunction) {
  51304. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51305. }
  51306. else {
  51307. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51308. }
  51309. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51310. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51311. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51312. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51313. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51314. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51315. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51316. }
  51317. };
  51318. ParticleSystem.prototype._getEffect = function () {
  51319. if (this._customEffect) {
  51320. return this._customEffect;
  51321. }
  51322. ;
  51323. var defines = [];
  51324. if (this._scene.clipPlane) {
  51325. defines.push("#define CLIPPLANE");
  51326. }
  51327. if (this._isAnimationSheetEnabled) {
  51328. defines.push("#define ANIMATESHEET");
  51329. }
  51330. // Effect
  51331. var join = defines.join("\n");
  51332. if (this._cachedDefines !== join) {
  51333. this._cachedDefines = join;
  51334. var attributesNamesOrOptions;
  51335. var effectCreationOption;
  51336. if (this._isAnimationSheetEnabled) {
  51337. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51338. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51339. }
  51340. else {
  51341. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51342. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51343. }
  51344. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51345. }
  51346. return this._effect;
  51347. };
  51348. /**
  51349. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51350. */
  51351. ParticleSystem.prototype.animate = function () {
  51352. if (!this._started)
  51353. return;
  51354. var effect = this._getEffect();
  51355. // Check
  51356. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51357. return;
  51358. if (this._currentRenderId === this._scene.getRenderId()) {
  51359. return;
  51360. }
  51361. this._currentRenderId = this._scene.getRenderId();
  51362. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51363. // determine the number of particles we need to create
  51364. var newParticles;
  51365. if (this.manualEmitCount > -1) {
  51366. newParticles = this.manualEmitCount;
  51367. this._newPartsExcess = 0;
  51368. this.manualEmitCount = 0;
  51369. }
  51370. else {
  51371. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51372. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51373. }
  51374. if (this._newPartsExcess > 1.0) {
  51375. newParticles += this._newPartsExcess >> 0;
  51376. this._newPartsExcess -= this._newPartsExcess >> 0;
  51377. }
  51378. this._alive = false;
  51379. if (!this._stopped) {
  51380. this._actualFrame += this._scaledUpdateSpeed;
  51381. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51382. this.stop();
  51383. }
  51384. else {
  51385. newParticles = 0;
  51386. }
  51387. this._update(newParticles);
  51388. // Stopped?
  51389. if (this._stopped) {
  51390. if (!this._alive) {
  51391. this._started = false;
  51392. if (this.onAnimationEnd) {
  51393. this.onAnimationEnd();
  51394. }
  51395. if (this.disposeOnStop) {
  51396. this._scene._toBeDisposed.push(this);
  51397. }
  51398. }
  51399. }
  51400. // Animation sheet
  51401. if (this._isAnimationSheetEnabled) {
  51402. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51403. }
  51404. else {
  51405. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51406. }
  51407. // Update VBO
  51408. var offset = 0;
  51409. for (var index = 0; index < this._particles.length; index++) {
  51410. var particle = this._particles[index];
  51411. this._appendParticleVertexes(offset, particle);
  51412. offset += 4;
  51413. }
  51414. if (this._vertexBuffer) {
  51415. this._vertexBuffer.update(this._vertexData);
  51416. }
  51417. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  51418. this.stop();
  51419. }
  51420. };
  51421. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51422. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51423. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51424. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51425. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51426. };
  51427. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51428. this._appendParticleVertex(offset++, particle, 0, 0);
  51429. this._appendParticleVertex(offset++, particle, 1, 0);
  51430. this._appendParticleVertex(offset++, particle, 1, 1);
  51431. this._appendParticleVertex(offset++, particle, 0, 1);
  51432. };
  51433. /**
  51434. * Rebuilds the particle system.
  51435. */
  51436. ParticleSystem.prototype.rebuild = function () {
  51437. this._createIndexBuffer();
  51438. if (this._vertexBuffer) {
  51439. this._vertexBuffer._rebuild();
  51440. }
  51441. };
  51442. /**
  51443. * Renders the particle system in its current state.
  51444. * @returns the current number of particles
  51445. */
  51446. ParticleSystem.prototype.render = function () {
  51447. var effect = this._getEffect();
  51448. // Check
  51449. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51450. return 0;
  51451. }
  51452. var engine = this._scene.getEngine();
  51453. // Render
  51454. engine.enableEffect(effect);
  51455. engine.setState(false);
  51456. var viewMatrix = this._scene.getViewMatrix();
  51457. effect.setTexture("diffuseSampler", this.particleTexture);
  51458. effect.setMatrix("view", viewMatrix);
  51459. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51460. if (this._isAnimationSheetEnabled) {
  51461. var baseSize = this.particleTexture.getBaseSize();
  51462. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51463. }
  51464. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51465. if (this._scene.clipPlane) {
  51466. var clipPlane = this._scene.clipPlane;
  51467. var invView = viewMatrix.clone();
  51468. invView.invert();
  51469. effect.setMatrix("invView", invView);
  51470. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51471. }
  51472. // VBOs
  51473. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51474. // Draw order
  51475. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51476. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51477. }
  51478. else {
  51479. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51480. }
  51481. if (this.forceDepthWrite) {
  51482. engine.setDepthWrite(true);
  51483. }
  51484. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51485. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51486. return this._particles.length;
  51487. };
  51488. /**
  51489. * Disposes the particle system and free the associated resources
  51490. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51491. */
  51492. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51493. if (disposeTexture === void 0) { disposeTexture = true; }
  51494. if (this._vertexBuffer) {
  51495. this._vertexBuffer.dispose();
  51496. this._vertexBuffer = null;
  51497. }
  51498. if (this._indexBuffer) {
  51499. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51500. this._indexBuffer = null;
  51501. }
  51502. if (disposeTexture && this.particleTexture) {
  51503. this.particleTexture.dispose();
  51504. this.particleTexture = null;
  51505. }
  51506. this._removeFromRoot();
  51507. // Remove from scene
  51508. var index = this._scene.particleSystems.indexOf(this);
  51509. if (index > -1) {
  51510. this._scene.particleSystems.splice(index, 1);
  51511. }
  51512. // Callback
  51513. this.onDisposeObservable.notifyObservers(this);
  51514. this.onDisposeObservable.clear();
  51515. };
  51516. /**
  51517. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51518. * @param radius The radius of the sphere to emit from
  51519. * @returns the emitter
  51520. */
  51521. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51522. if (radius === void 0) { radius = 1; }
  51523. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51524. this.particleEmitterType = particleEmitter;
  51525. return particleEmitter;
  51526. };
  51527. /**
  51528. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51529. * @param radius The radius of the sphere to emit from
  51530. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51531. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51532. * @returns the emitter
  51533. */
  51534. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51535. if (radius === void 0) { radius = 1; }
  51536. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51537. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51538. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51539. this.particleEmitterType = particleEmitter;
  51540. return particleEmitter;
  51541. };
  51542. /**
  51543. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51544. * @param radius The radius of the cone to emit from
  51545. * @param angle The base angle of the cone
  51546. * @returns the emitter
  51547. */
  51548. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51549. if (radius === void 0) { radius = 1; }
  51550. if (angle === void 0) { angle = Math.PI / 4; }
  51551. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51552. this.particleEmitterType = particleEmitter;
  51553. return particleEmitter;
  51554. };
  51555. // 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.
  51556. /**
  51557. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51558. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51559. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51560. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51561. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51562. * @returns the emitter
  51563. */
  51564. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51565. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51566. this.direction1 = direction1;
  51567. this.direction2 = direction2;
  51568. this.minEmitBox = minEmitBox;
  51569. this.maxEmitBox = maxEmitBox;
  51570. this.particleEmitterType = particleEmitter;
  51571. return particleEmitter;
  51572. };
  51573. // Clone
  51574. /**
  51575. * Clones the particle system.
  51576. * @param name The name of the cloned object
  51577. * @param newEmitter The new emitter to use
  51578. * @returns the cloned particle system
  51579. */
  51580. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51581. var custom = null;
  51582. var program = null;
  51583. if (this.customShader != null) {
  51584. program = this.customShader;
  51585. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51586. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51587. }
  51588. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51589. result.customShader = program;
  51590. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51591. if (newEmitter === undefined) {
  51592. newEmitter = this.emitter;
  51593. }
  51594. result.emitter = newEmitter;
  51595. if (this.particleTexture) {
  51596. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51597. }
  51598. if (!this.preventAutoStart) {
  51599. result.start();
  51600. }
  51601. return result;
  51602. };
  51603. /**
  51604. * Serializes the particle system to a JSON object.
  51605. * @returns the JSON object
  51606. */
  51607. ParticleSystem.prototype.serialize = function () {
  51608. var serializationObject = {};
  51609. serializationObject.name = this.name;
  51610. serializationObject.id = this.id;
  51611. // Emitter
  51612. if (this.emitter.position) {
  51613. var emitterMesh = this.emitter;
  51614. serializationObject.emitterId = emitterMesh.id;
  51615. }
  51616. else {
  51617. var emitterPosition = this.emitter;
  51618. serializationObject.emitter = emitterPosition.asArray();
  51619. }
  51620. serializationObject.capacity = this.getCapacity();
  51621. if (this.particleTexture) {
  51622. serializationObject.textureName = this.particleTexture.name;
  51623. }
  51624. // Animations
  51625. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51626. // Particle system
  51627. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51628. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51629. serializationObject.minSize = this.minSize;
  51630. serializationObject.maxSize = this.maxSize;
  51631. serializationObject.minEmitPower = this.minEmitPower;
  51632. serializationObject.maxEmitPower = this.maxEmitPower;
  51633. serializationObject.minLifeTime = this.minLifeTime;
  51634. serializationObject.maxLifeTime = this.maxLifeTime;
  51635. serializationObject.emitRate = this.emitRate;
  51636. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51637. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51638. serializationObject.gravity = this.gravity.asArray();
  51639. serializationObject.direction1 = this.direction1.asArray();
  51640. serializationObject.direction2 = this.direction2.asArray();
  51641. serializationObject.color1 = this.color1.asArray();
  51642. serializationObject.color2 = this.color2.asArray();
  51643. serializationObject.colorDead = this.colorDead.asArray();
  51644. serializationObject.updateSpeed = this.updateSpeed;
  51645. serializationObject.targetStopDuration = this.targetStopDuration;
  51646. serializationObject.textureMask = this.textureMask.asArray();
  51647. serializationObject.blendMode = this.blendMode;
  51648. serializationObject.customShader = this.customShader;
  51649. serializationObject.preventAutoStart = this.preventAutoStart;
  51650. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51651. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51652. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51653. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51654. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51655. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51656. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51657. // Emitter
  51658. if (this.particleEmitterType) {
  51659. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51660. }
  51661. return serializationObject;
  51662. };
  51663. /**
  51664. * Parses a JSON object to create a particle system.
  51665. * @param parsedParticleSystem The JSON object to parse
  51666. * @param scene The scene to create the particle system in
  51667. * @param rootUrl The root url to use to load external dependencies like texture
  51668. * @returns the Parsed particle system
  51669. */
  51670. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51671. var name = parsedParticleSystem.name;
  51672. var custom = null;
  51673. var program = null;
  51674. if (parsedParticleSystem.customShader) {
  51675. program = parsedParticleSystem.customShader;
  51676. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51677. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51678. }
  51679. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51680. particleSystem.customShader = program;
  51681. if (parsedParticleSystem.id) {
  51682. particleSystem.id = parsedParticleSystem.id;
  51683. }
  51684. // Auto start
  51685. if (parsedParticleSystem.preventAutoStart) {
  51686. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51687. }
  51688. // Texture
  51689. if (parsedParticleSystem.textureName) {
  51690. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51691. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51692. }
  51693. // Emitter
  51694. if (parsedParticleSystem.emitterId) {
  51695. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51696. }
  51697. else {
  51698. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51699. }
  51700. // Animations
  51701. if (parsedParticleSystem.animations) {
  51702. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51703. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51704. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51705. }
  51706. }
  51707. if (parsedParticleSystem.autoAnimate) {
  51708. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51709. }
  51710. // Particle system
  51711. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51712. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51713. particleSystem.minSize = parsedParticleSystem.minSize;
  51714. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51715. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51716. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51717. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51718. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51719. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51720. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51721. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51722. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51723. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51724. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51725. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51726. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51727. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51728. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51729. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51730. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51731. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51732. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51733. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51734. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51735. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51736. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51737. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51738. if (!particleSystem.preventAutoStart) {
  51739. particleSystem.start();
  51740. }
  51741. return particleSystem;
  51742. };
  51743. /**
  51744. * Source color is added to the destination color without alpha affecting the result.
  51745. */
  51746. ParticleSystem.BLENDMODE_ONEONE = 0;
  51747. /**
  51748. * Blend current color and particle color using particle’s alpha.
  51749. */
  51750. ParticleSystem.BLENDMODE_STANDARD = 1;
  51751. return ParticleSystem;
  51752. }());
  51753. BABYLON.ParticleSystem = ParticleSystem;
  51754. })(BABYLON || (BABYLON = {}));
  51755. //# sourceMappingURL=babylon.particleSystem.js.map
  51756. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51757. var BABYLON;
  51758. (function (BABYLON) {
  51759. /**
  51760. * Particle emitter emitting particles from the inside of a box.
  51761. * It emits the particles randomly between 2 given directions.
  51762. */
  51763. var BoxParticleEmitter = /** @class */ (function () {
  51764. /**
  51765. * Creates a new instance of @see BoxParticleEmitter
  51766. */
  51767. function BoxParticleEmitter() {
  51768. /**
  51769. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51770. */
  51771. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51772. /**
  51773. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51774. */
  51775. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51776. /**
  51777. * 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.
  51778. */
  51779. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51780. /**
  51781. * 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.
  51782. */
  51783. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51784. }
  51785. /**
  51786. * Called by the particle System when the direction is computed for the created particle.
  51787. * @param emitPower is the power of the particle (speed)
  51788. * @param worldMatrix is the world matrix of the particle system
  51789. * @param directionToUpdate is the direction vector to update with the result
  51790. * @param particle is the particle we are computed the direction for
  51791. */
  51792. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51793. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51794. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51795. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51796. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51797. };
  51798. /**
  51799. * Called by the particle System when the position is computed for the created particle.
  51800. * @param worldMatrix is the world matrix of the particle system
  51801. * @param positionToUpdate is the position vector to update with the result
  51802. * @param particle is the particle we are computed the position for
  51803. */
  51804. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51805. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51806. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51807. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51808. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51809. };
  51810. /**
  51811. * Clones the current emitter and returns a copy of it
  51812. * @returns the new emitter
  51813. */
  51814. BoxParticleEmitter.prototype.clone = function () {
  51815. var newOne = new BoxParticleEmitter();
  51816. BABYLON.Tools.DeepCopy(this, newOne);
  51817. return newOne;
  51818. };
  51819. /**
  51820. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51821. * @param effect defines the update shader
  51822. */
  51823. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51824. effect.setVector3("direction1", this.direction1);
  51825. effect.setVector3("direction2", this.direction2);
  51826. effect.setVector3("minEmitBox", this.minEmitBox);
  51827. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51828. };
  51829. /**
  51830. * Returns a string to use to update the GPU particles update shader
  51831. * @returns a string containng the defines string
  51832. */
  51833. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51834. return "#define BOXEMITTER";
  51835. };
  51836. /**
  51837. * Returns the string "BoxEmitter"
  51838. * @returns a string containing the class name
  51839. */
  51840. BoxParticleEmitter.prototype.getClassName = function () {
  51841. return "BoxEmitter";
  51842. };
  51843. /**
  51844. * Serializes the particle system to a JSON object.
  51845. * @returns the JSON object
  51846. */
  51847. BoxParticleEmitter.prototype.serialize = function () {
  51848. var serializationObject = {};
  51849. serializationObject.type = this.getClassName();
  51850. serializationObject.direction1 = this.direction1.asArray();
  51851. ;
  51852. serializationObject.direction2 = this.direction2.asArray();
  51853. ;
  51854. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51855. ;
  51856. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51857. ;
  51858. return serializationObject;
  51859. };
  51860. /**
  51861. * Parse properties from a JSON object
  51862. * @param serializationObject defines the JSON object
  51863. */
  51864. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51865. this.direction1.copyFrom(serializationObject.direction1);
  51866. this.direction2.copyFrom(serializationObject.direction2);
  51867. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51868. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51869. };
  51870. return BoxParticleEmitter;
  51871. }());
  51872. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51873. })(BABYLON || (BABYLON = {}));
  51874. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51875. var BABYLON;
  51876. (function (BABYLON) {
  51877. /**
  51878. * Particle emitter emitting particles from the inside of a cone.
  51879. * It emits the particles alongside the cone volume from the base to the particle.
  51880. * The emission direction might be randomized.
  51881. */
  51882. var ConeParticleEmitter = /** @class */ (function () {
  51883. /**
  51884. * Creates a new instance of @see ConeParticleEmitter
  51885. * @param radius the radius of the emission cone (1 by default)
  51886. * @param angles the cone base angle (PI by default)
  51887. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51888. */
  51889. function ConeParticleEmitter(radius,
  51890. /**
  51891. * The radius of the emission cone.
  51892. */
  51893. angle,
  51894. /**
  51895. * The cone base angle.
  51896. */
  51897. directionRandomizer) {
  51898. if (radius === void 0) { radius = 1; }
  51899. if (angle === void 0) { angle = Math.PI; }
  51900. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51901. this.angle = angle;
  51902. this.directionRandomizer = directionRandomizer;
  51903. this.radius = radius;
  51904. }
  51905. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51906. /**
  51907. * Gets the radius of the emission cone.
  51908. */
  51909. get: function () {
  51910. return this._radius;
  51911. },
  51912. /**
  51913. * Sets the radius of the emission cone.
  51914. */
  51915. set: function (value) {
  51916. this._radius = value;
  51917. if (this.angle !== 0) {
  51918. this._height = value / Math.tan(this.angle / 2);
  51919. }
  51920. else {
  51921. this._height = 1;
  51922. }
  51923. },
  51924. enumerable: true,
  51925. configurable: true
  51926. });
  51927. /**
  51928. * Called by the particle System when the direction is computed for the created particle.
  51929. * @param emitPower is the power of the particle (speed)
  51930. * @param worldMatrix is the world matrix of the particle system
  51931. * @param directionToUpdate is the direction vector to update with the result
  51932. * @param particle is the particle we are computed the direction for
  51933. */
  51934. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51935. if (this.angle === 0) {
  51936. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51937. }
  51938. else {
  51939. // measure the direction Vector from the emitter to the particle.
  51940. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51941. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51942. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51943. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51944. direction.x += randX;
  51945. direction.y += randY;
  51946. direction.z += randZ;
  51947. direction.normalize();
  51948. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51949. }
  51950. };
  51951. /**
  51952. * Called by the particle System when the position is computed for the created particle.
  51953. * @param worldMatrix is the world matrix of the particle system
  51954. * @param positionToUpdate is the position vector to update with the result
  51955. * @param particle is the particle we are computed the position for
  51956. */
  51957. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51958. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51959. var h = BABYLON.Scalar.RandomRange(0, 1);
  51960. // Better distribution in a cone at normal angles.
  51961. h = 1 - h * h;
  51962. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51963. radius = radius * h / this._height;
  51964. var randX = radius * Math.sin(s);
  51965. var randZ = radius * Math.cos(s);
  51966. var randY = h * this._height;
  51967. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51968. };
  51969. /**
  51970. * Clones the current emitter and returns a copy of it
  51971. * @returns the new emitter
  51972. */
  51973. ConeParticleEmitter.prototype.clone = function () {
  51974. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51975. BABYLON.Tools.DeepCopy(this, newOne);
  51976. return newOne;
  51977. };
  51978. /**
  51979. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51980. * @param effect defines the update shader
  51981. */
  51982. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51983. effect.setFloat("radius", this.radius);
  51984. effect.setFloat("angle", this.angle);
  51985. effect.setFloat("height", this._height);
  51986. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51987. };
  51988. /**
  51989. * Returns a string to use to update the GPU particles update shader
  51990. * @returns a string containng the defines string
  51991. */
  51992. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51993. return "#define CONEEMITTER";
  51994. };
  51995. /**
  51996. * Returns the string "BoxEmitter"
  51997. * @returns a string containing the class name
  51998. */
  51999. ConeParticleEmitter.prototype.getClassName = function () {
  52000. return "ConeEmitter";
  52001. };
  52002. /**
  52003. * Serializes the particle system to a JSON object.
  52004. * @returns the JSON object
  52005. */
  52006. ConeParticleEmitter.prototype.serialize = function () {
  52007. var serializationObject = {};
  52008. serializationObject.type = this.getClassName();
  52009. serializationObject.radius = this.radius;
  52010. serializationObject.angle = this.angle;
  52011. serializationObject.directionRandomizer = this.directionRandomizer;
  52012. return serializationObject;
  52013. };
  52014. /**
  52015. * Parse properties from a JSON object
  52016. * @param serializationObject defines the JSON object
  52017. */
  52018. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52019. this.radius = serializationObject.radius;
  52020. this.angle = serializationObject.angle;
  52021. this.directionRandomizer = serializationObject.directionRandomizer;
  52022. };
  52023. return ConeParticleEmitter;
  52024. }());
  52025. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52026. })(BABYLON || (BABYLON = {}));
  52027. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52028. var BABYLON;
  52029. (function (BABYLON) {
  52030. /**
  52031. * Particle emitter emitting particles from the inside of a sphere.
  52032. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52033. */
  52034. var SphereParticleEmitter = /** @class */ (function () {
  52035. /**
  52036. * Creates a new instance of @see SphereParticleEmitter
  52037. * @param radius the radius of the emission sphere (1 by default)
  52038. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52039. */
  52040. function SphereParticleEmitter(
  52041. /**
  52042. * The radius of the emission sphere.
  52043. */
  52044. radius,
  52045. /**
  52046. * How much to randomize the particle direction [0-1].
  52047. */
  52048. directionRandomizer) {
  52049. if (radius === void 0) { radius = 1; }
  52050. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52051. this.radius = radius;
  52052. this.directionRandomizer = directionRandomizer;
  52053. }
  52054. /**
  52055. * Called by the particle System when the direction is computed for the created particle.
  52056. * @param emitPower is the power of the particle (speed)
  52057. * @param worldMatrix is the world matrix of the particle system
  52058. * @param directionToUpdate is the direction vector to update with the result
  52059. * @param particle is the particle we are computed the direction for
  52060. */
  52061. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52062. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52063. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52064. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52065. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52066. direction.x += randX;
  52067. direction.y += randY;
  52068. direction.z += randZ;
  52069. direction.normalize();
  52070. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52071. };
  52072. /**
  52073. * Called by the particle System when the position is computed for the created particle.
  52074. * @param worldMatrix is the world matrix of the particle system
  52075. * @param positionToUpdate is the position vector to update with the result
  52076. * @param particle is the particle we are computed the position for
  52077. */
  52078. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52079. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52080. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52081. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52082. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52083. var randY = randRadius * Math.cos(theta);
  52084. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52085. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52086. };
  52087. /**
  52088. * Clones the current emitter and returns a copy of it
  52089. * @returns the new emitter
  52090. */
  52091. SphereParticleEmitter.prototype.clone = function () {
  52092. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52093. BABYLON.Tools.DeepCopy(this, newOne);
  52094. return newOne;
  52095. };
  52096. /**
  52097. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52098. * @param effect defines the update shader
  52099. */
  52100. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52101. effect.setFloat("radius", this.radius);
  52102. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52103. };
  52104. /**
  52105. * Returns a string to use to update the GPU particles update shader
  52106. * @returns a string containng the defines string
  52107. */
  52108. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52109. return "#define SPHEREEMITTER";
  52110. };
  52111. /**
  52112. * Returns the string "SphereParticleEmitter"
  52113. * @returns a string containing the class name
  52114. */
  52115. SphereParticleEmitter.prototype.getClassName = function () {
  52116. return "SphereParticleEmitter";
  52117. };
  52118. /**
  52119. * Serializes the particle system to a JSON object.
  52120. * @returns the JSON object
  52121. */
  52122. SphereParticleEmitter.prototype.serialize = function () {
  52123. var serializationObject = {};
  52124. serializationObject.type = this.getClassName();
  52125. serializationObject.radius = this.radius;
  52126. serializationObject.directionRandomizer = this.directionRandomizer;
  52127. return serializationObject;
  52128. };
  52129. /**
  52130. * Parse properties from a JSON object
  52131. * @param serializationObject defines the JSON object
  52132. */
  52133. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52134. this.radius = serializationObject.radius;
  52135. this.directionRandomizer = serializationObject.directionRandomizer;
  52136. };
  52137. return SphereParticleEmitter;
  52138. }());
  52139. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52140. /**
  52141. * Particle emitter emitting particles from the inside of a sphere.
  52142. * It emits the particles randomly between two vectors.
  52143. */
  52144. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52145. __extends(SphereDirectedParticleEmitter, _super);
  52146. /**
  52147. * Creates a new instance of @see SphereDirectedParticleEmitter
  52148. * @param radius the radius of the emission sphere (1 by default)
  52149. * @param direction1 the min limit of the emission direction (up vector by default)
  52150. * @param direction2 the max limit of the emission direction (up vector by default)
  52151. */
  52152. function SphereDirectedParticleEmitter(radius,
  52153. /**
  52154. * The min limit of the emission direction.
  52155. */
  52156. direction1,
  52157. /**
  52158. * The max limit of the emission direction.
  52159. */
  52160. direction2) {
  52161. if (radius === void 0) { radius = 1; }
  52162. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52163. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52164. var _this = _super.call(this, radius) || this;
  52165. _this.direction1 = direction1;
  52166. _this.direction2 = direction2;
  52167. return _this;
  52168. }
  52169. /**
  52170. * Called by the particle System when the direction is computed for the created particle.
  52171. * @param emitPower is the power of the particle (speed)
  52172. * @param worldMatrix is the world matrix of the particle system
  52173. * @param directionToUpdate is the direction vector to update with the result
  52174. * @param particle is the particle we are computed the direction for
  52175. */
  52176. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52177. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52178. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52179. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52180. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52181. };
  52182. /**
  52183. * Clones the current emitter and returns a copy of it
  52184. * @returns the new emitter
  52185. */
  52186. SphereDirectedParticleEmitter.prototype.clone = function () {
  52187. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52188. BABYLON.Tools.DeepCopy(this, newOne);
  52189. return newOne;
  52190. };
  52191. /**
  52192. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52193. * @param effect defines the update shader
  52194. */
  52195. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52196. effect.setFloat("radius", this.radius);
  52197. effect.setVector3("direction1", this.direction1);
  52198. effect.setVector3("direction2", this.direction2);
  52199. };
  52200. /**
  52201. * Returns a string to use to update the GPU particles update shader
  52202. * @returns a string containng the defines string
  52203. */
  52204. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52205. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52206. };
  52207. /**
  52208. * Returns the string "SphereDirectedParticleEmitter"
  52209. * @returns a string containing the class name
  52210. */
  52211. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52212. return "SphereDirectedParticleEmitter";
  52213. };
  52214. /**
  52215. * Serializes the particle system to a JSON object.
  52216. * @returns the JSON object
  52217. */
  52218. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52219. var serializationObject = _super.prototype.serialize.call(this);
  52220. ;
  52221. serializationObject.direction1 = this.direction1.asArray();
  52222. ;
  52223. serializationObject.direction2 = this.direction2.asArray();
  52224. ;
  52225. return serializationObject;
  52226. };
  52227. /**
  52228. * Parse properties from a JSON object
  52229. * @param serializationObject defines the JSON object
  52230. */
  52231. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52232. _super.prototype.parse.call(this, serializationObject);
  52233. this.direction1.copyFrom(serializationObject.direction1);
  52234. this.direction2.copyFrom(serializationObject.direction2);
  52235. };
  52236. return SphereDirectedParticleEmitter;
  52237. }(SphereParticleEmitter));
  52238. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52239. })(BABYLON || (BABYLON = {}));
  52240. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52241. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52242. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52243. s = arguments[i];
  52244. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52245. t[p] = s[p];
  52246. }
  52247. return t;
  52248. };
  52249. var BABYLON;
  52250. (function (BABYLON) {
  52251. /**
  52252. * This represents a GPU particle system in Babylon
  52253. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52254. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52255. */
  52256. var GPUParticleSystem = /** @class */ (function () {
  52257. /**
  52258. * Instantiates a GPU particle system.
  52259. * 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.
  52260. * @param name The name of the particle system
  52261. * @param capacity The max number of particles alive at the same time
  52262. * @param scene The scene the particle system belongs to
  52263. */
  52264. function GPUParticleSystem(name, options, scene) {
  52265. /**
  52266. * The emitter represents the Mesh or position we are attaching the particle system to.
  52267. */
  52268. this.emitter = null;
  52269. /**
  52270. * The rendering group used by the Particle system to chose when to render.
  52271. */
  52272. this.renderingGroupId = 0;
  52273. /**
  52274. * The layer mask we are rendering the particles through.
  52275. */
  52276. this.layerMask = 0x0FFFFFFF;
  52277. this._targetIndex = 0;
  52278. this._currentRenderId = -1;
  52279. this._started = false;
  52280. this._stopped = false;
  52281. this._timeDelta = 0;
  52282. this._attributesStrideSize = 14;
  52283. this._actualFrame = 0;
  52284. /**
  52285. * List of animations used by the particle system.
  52286. */
  52287. this.animations = [];
  52288. /**
  52289. * An event triggered when the system is disposed.
  52290. */
  52291. this.onDisposeObservable = new BABYLON.Observable();
  52292. /**
  52293. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52294. */
  52295. this.updateSpeed = 0.01;
  52296. /**
  52297. * The amount of time the particle system is running (depends of the overall update speed).
  52298. */
  52299. this.targetStopDuration = 0;
  52300. /**
  52301. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52302. */
  52303. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  52304. /**
  52305. * Minimum life time of emitting particles.
  52306. */
  52307. this.minLifeTime = 1;
  52308. /**
  52309. * Maximum life time of emitting particles.
  52310. */
  52311. this.maxLifeTime = 1;
  52312. /**
  52313. * Minimum Size of emitting particles.
  52314. */
  52315. this.minSize = 1;
  52316. /**
  52317. * Maximum Size of emitting particles.
  52318. */
  52319. this.maxSize = 1;
  52320. /**
  52321. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52322. */
  52323. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52324. /**
  52325. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52326. */
  52327. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52328. /**
  52329. * Color the particle will have at the end of its lifetime.
  52330. */
  52331. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  52332. /**
  52333. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  52334. */
  52335. this.emitRate = 100;
  52336. /**
  52337. * You can use gravity if you want to give an orientation to your particles.
  52338. */
  52339. this.gravity = BABYLON.Vector3.Zero();
  52340. /**
  52341. * Minimum power of emitting particles.
  52342. */
  52343. this.minEmitPower = 1;
  52344. /**
  52345. * Maximum power of emitting particles.
  52346. */
  52347. this.maxEmitPower = 1;
  52348. /**
  52349. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  52350. * to override the particles.
  52351. */
  52352. this.forceDepthWrite = false;
  52353. this.id = name;
  52354. this.name = name;
  52355. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52356. this._engine = this._scene.getEngine();
  52357. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  52358. this._capacity = fullOptions.capacity;
  52359. this._activeCount = fullOptions.capacity;
  52360. this._currentActiveCount = 0;
  52361. this._scene.particleSystems.push(this);
  52362. this._updateEffectOptions = {
  52363. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  52364. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  52365. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  52366. uniformBuffersNames: [],
  52367. samplers: ["randomSampler"],
  52368. defines: "",
  52369. fallbacks: null,
  52370. onCompiled: null,
  52371. onError: null,
  52372. indexParameters: null,
  52373. maxSimultaneousLights: 0,
  52374. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  52375. };
  52376. // Random data
  52377. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  52378. var d = [];
  52379. for (var i = 0; i < maxTextureSize; ++i) {
  52380. d.push(Math.random());
  52381. d.push(Math.random());
  52382. d.push(Math.random());
  52383. d.push(Math.random());
  52384. }
  52385. 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);
  52386. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52387. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52388. this._randomTextureSize = maxTextureSize;
  52389. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52390. }
  52391. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  52392. /**
  52393. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  52394. */
  52395. get: function () {
  52396. if (!BABYLON.Engine.LastCreatedEngine) {
  52397. return false;
  52398. }
  52399. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  52400. },
  52401. enumerable: true,
  52402. configurable: true
  52403. });
  52404. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  52405. /**
  52406. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52407. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52408. */
  52409. get: function () {
  52410. if (this.particleEmitterType.direction1) {
  52411. return this.particleEmitterType.direction1;
  52412. }
  52413. return BABYLON.Vector3.Zero();
  52414. },
  52415. set: function (value) {
  52416. if (this.particleEmitterType.direction1) {
  52417. this.particleEmitterType.direction1 = value;
  52418. }
  52419. },
  52420. enumerable: true,
  52421. configurable: true
  52422. });
  52423. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  52424. /**
  52425. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52426. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52427. */
  52428. get: function () {
  52429. if (this.particleEmitterType.direction2) {
  52430. return this.particleEmitterType.direction2;
  52431. }
  52432. return BABYLON.Vector3.Zero();
  52433. },
  52434. set: function (value) {
  52435. if (this.particleEmitterType.direction2) {
  52436. this.particleEmitterType.direction2 = value;
  52437. }
  52438. },
  52439. enumerable: true,
  52440. configurable: true
  52441. });
  52442. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  52443. /**
  52444. * 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.
  52445. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52446. */
  52447. get: function () {
  52448. if (this.particleEmitterType.minEmitBox) {
  52449. return this.particleEmitterType.minEmitBox;
  52450. }
  52451. return BABYLON.Vector3.Zero();
  52452. },
  52453. set: function (value) {
  52454. if (this.particleEmitterType.minEmitBox) {
  52455. this.particleEmitterType.minEmitBox = value;
  52456. }
  52457. },
  52458. enumerable: true,
  52459. configurable: true
  52460. });
  52461. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  52462. /**
  52463. * 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.
  52464. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52465. */
  52466. get: function () {
  52467. if (this.particleEmitterType.maxEmitBox) {
  52468. return this.particleEmitterType.maxEmitBox;
  52469. }
  52470. return BABYLON.Vector3.Zero();
  52471. },
  52472. set: function (value) {
  52473. if (this.particleEmitterType.maxEmitBox) {
  52474. this.particleEmitterType.maxEmitBox = value;
  52475. }
  52476. },
  52477. enumerable: true,
  52478. configurable: true
  52479. });
  52480. /**
  52481. * Gets the maximum number of particles active at the same time.
  52482. * @returns The max number of active particles.
  52483. */
  52484. GPUParticleSystem.prototype.getCapacity = function () {
  52485. return this._capacity;
  52486. };
  52487. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  52488. /**
  52489. * Gets or set the number of active particles
  52490. */
  52491. get: function () {
  52492. return this._activeCount;
  52493. },
  52494. set: function (value) {
  52495. this._activeCount = Math.min(value, this._capacity);
  52496. },
  52497. enumerable: true,
  52498. configurable: true
  52499. });
  52500. /**
  52501. * Gets Wether the system has been started.
  52502. * @returns True if it has been started, otherwise false.
  52503. */
  52504. GPUParticleSystem.prototype.isStarted = function () {
  52505. return this._started;
  52506. };
  52507. /**
  52508. * Starts the particle system and begins to emit.
  52509. */
  52510. GPUParticleSystem.prototype.start = function () {
  52511. this._started = true;
  52512. this._stopped = false;
  52513. };
  52514. /**
  52515. * Stops the particle system.
  52516. */
  52517. GPUParticleSystem.prototype.stop = function () {
  52518. this._stopped = true;
  52519. };
  52520. /**
  52521. * Remove all active particles
  52522. */
  52523. GPUParticleSystem.prototype.reset = function () {
  52524. this._releaseBuffers();
  52525. this._releaseVAOs();
  52526. this._currentActiveCount = 0;
  52527. this._targetIndex = 0;
  52528. };
  52529. /**
  52530. * Returns the string "GPUParticleSystem"
  52531. * @returns a string containing the class name
  52532. */
  52533. GPUParticleSystem.prototype.getClassName = function () {
  52534. return "GPUParticleSystem";
  52535. };
  52536. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  52537. var updateVertexBuffers = {};
  52538. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  52539. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  52540. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  52541. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  52542. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  52543. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  52544. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  52545. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  52546. this._engine.bindArrayBuffer(null);
  52547. return vao;
  52548. };
  52549. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  52550. var renderVertexBuffers = {};
  52551. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  52552. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  52553. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  52554. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  52555. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  52556. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  52557. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  52558. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  52559. this._engine.bindArrayBuffer(null);
  52560. return vao;
  52561. };
  52562. GPUParticleSystem.prototype._initialize = function (force) {
  52563. if (force === void 0) { force = false; }
  52564. if (this._buffer0 && !force) {
  52565. return;
  52566. }
  52567. var engine = this._scene.getEngine();
  52568. var data = new Array();
  52569. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  52570. // position
  52571. data.push(0.0);
  52572. data.push(0.0);
  52573. data.push(0.0);
  52574. // Age and life
  52575. data.push(0.0); // create the particle as a dead one to create a new one at start
  52576. data.push(0.0);
  52577. // Seed
  52578. data.push(Math.random());
  52579. // Size
  52580. data.push(0.0);
  52581. // color
  52582. data.push(0.0);
  52583. data.push(0.0);
  52584. data.push(0.0);
  52585. data.push(0.0);
  52586. // direction
  52587. data.push(0.0);
  52588. data.push(0.0);
  52589. data.push(0.0);
  52590. }
  52591. // Sprite data
  52592. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  52593. -0.5, 0.5, 0, 1,
  52594. -0.5, -0.5, 0, 0,
  52595. 0.5, -0.5, 1, 0]);
  52596. // Buffers
  52597. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52598. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52599. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  52600. // Update VAO
  52601. this._updateVAO = [];
  52602. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  52603. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  52604. // Render VAO
  52605. this._renderVAO = [];
  52606. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  52607. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  52608. // Links
  52609. this._sourceBuffer = this._buffer0;
  52610. this._targetBuffer = this._buffer1;
  52611. };
  52612. /** @ignore */
  52613. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  52614. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  52615. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  52616. return;
  52617. }
  52618. this._updateEffectOptions.defines = defines;
  52619. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  52620. };
  52621. /** @ignore */
  52622. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  52623. var defines = "";
  52624. if (this._scene.clipPlane) {
  52625. defines = "\n#define CLIPPLANE";
  52626. }
  52627. if (this._renderEffect && this._renderEffect.defines === defines) {
  52628. return;
  52629. }
  52630. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  52631. };
  52632. /**
  52633. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52634. */
  52635. GPUParticleSystem.prototype.animate = function () {
  52636. if (!this._stopped) {
  52637. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  52638. this._actualFrame += this._timeDelta;
  52639. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52640. this.stop();
  52641. }
  52642. };
  52643. /**
  52644. * Renders the particle system in its current state.
  52645. * @returns the current number of particles
  52646. */
  52647. GPUParticleSystem.prototype.render = function () {
  52648. if (!this._started) {
  52649. return 0;
  52650. }
  52651. this._recreateUpdateEffect();
  52652. this._recreateRenderEffect();
  52653. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  52654. return 0;
  52655. }
  52656. if (this._currentRenderId === this._scene.getRenderId()) {
  52657. return 0;
  52658. }
  52659. this._currentRenderId = this._scene.getRenderId();
  52660. // Get everything ready to render
  52661. this._initialize();
  52662. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  52663. // Enable update effect
  52664. this._engine.enableEffect(this._updateEffect);
  52665. this._engine.setState(false);
  52666. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  52667. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  52668. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  52669. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  52670. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  52671. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  52672. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  52673. this._updateEffect.setDirectColor4("color1", this.color1);
  52674. this._updateEffect.setDirectColor4("color2", this.color2);
  52675. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  52676. this._updateEffect.setVector3("gravity", this.gravity);
  52677. if (this.particleEmitterType) {
  52678. this.particleEmitterType.applyToShader(this._updateEffect);
  52679. }
  52680. var emitterWM;
  52681. if (this.emitter.position) {
  52682. var emitterMesh = this.emitter;
  52683. emitterWM = emitterMesh.getWorldMatrix();
  52684. }
  52685. else {
  52686. var emitterPosition = this.emitter;
  52687. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52688. }
  52689. this._updateEffect.setMatrix("emitterWM", emitterWM);
  52690. // Bind source VAO
  52691. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  52692. // Update
  52693. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  52694. this._engine.setRasterizerState(false);
  52695. this._engine.beginTransformFeedback();
  52696. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  52697. this._engine.endTransformFeedback();
  52698. this._engine.setRasterizerState(true);
  52699. this._engine.bindTransformFeedbackBuffer(null);
  52700. // Enable render effect
  52701. this._engine.enableEffect(this._renderEffect);
  52702. var viewMatrix = this._scene.getViewMatrix();
  52703. this._renderEffect.setMatrix("view", viewMatrix);
  52704. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  52705. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  52706. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  52707. if (this._scene.clipPlane) {
  52708. var clipPlane = this._scene.clipPlane;
  52709. var invView = viewMatrix.clone();
  52710. invView.invert();
  52711. this._renderEffect.setMatrix("invView", invView);
  52712. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52713. }
  52714. // Draw order
  52715. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  52716. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52717. }
  52718. else {
  52719. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52720. }
  52721. if (this.forceDepthWrite) {
  52722. this._engine.setDepthWrite(true);
  52723. }
  52724. // Bind source VAO
  52725. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  52726. // Render
  52727. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  52728. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52729. // Switch VAOs
  52730. this._targetIndex++;
  52731. if (this._targetIndex === 2) {
  52732. this._targetIndex = 0;
  52733. }
  52734. // Switch buffers
  52735. var tmpBuffer = this._sourceBuffer;
  52736. this._sourceBuffer = this._targetBuffer;
  52737. this._targetBuffer = tmpBuffer;
  52738. return this._currentActiveCount;
  52739. };
  52740. /**
  52741. * Rebuilds the particle system
  52742. */
  52743. GPUParticleSystem.prototype.rebuild = function () {
  52744. this._initialize(true);
  52745. };
  52746. GPUParticleSystem.prototype._releaseBuffers = function () {
  52747. if (this._buffer0) {
  52748. this._buffer0.dispose();
  52749. this._buffer0 = null;
  52750. }
  52751. if (this._buffer1) {
  52752. this._buffer1.dispose();
  52753. this._buffer1 = null;
  52754. }
  52755. if (this._spriteBuffer) {
  52756. this._spriteBuffer.dispose();
  52757. this._spriteBuffer = null;
  52758. }
  52759. };
  52760. GPUParticleSystem.prototype._releaseVAOs = function () {
  52761. if (!this._updateVAO) {
  52762. return;
  52763. }
  52764. for (var index = 0; index < this._updateVAO.length; index++) {
  52765. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  52766. }
  52767. this._updateVAO = [];
  52768. for (var index = 0; index < this._renderVAO.length; index++) {
  52769. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  52770. }
  52771. this._renderVAO = [];
  52772. };
  52773. /**
  52774. * Disposes the particle system and free the associated resources
  52775. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52776. */
  52777. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  52778. if (disposeTexture === void 0) { disposeTexture = true; }
  52779. var index = this._scene.particleSystems.indexOf(this);
  52780. if (index > -1) {
  52781. this._scene.particleSystems.splice(index, 1);
  52782. }
  52783. this._releaseBuffers();
  52784. this._releaseVAOs();
  52785. if (this._randomTexture) {
  52786. this._randomTexture.dispose();
  52787. this._randomTexture = null;
  52788. }
  52789. if (disposeTexture && this.particleTexture) {
  52790. this.particleTexture.dispose();
  52791. this.particleTexture = null;
  52792. }
  52793. // Callback
  52794. this.onDisposeObservable.notifyObservers(this);
  52795. this.onDisposeObservable.clear();
  52796. };
  52797. /**
  52798. * Clones the particle system.
  52799. * @param name The name of the cloned object
  52800. * @param newEmitter The new emitter to use
  52801. * @returns the cloned particle system
  52802. */
  52803. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  52804. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  52805. BABYLON.Tools.DeepCopy(this, result);
  52806. if (newEmitter === undefined) {
  52807. newEmitter = this.emitter;
  52808. }
  52809. result.emitter = newEmitter;
  52810. if (this.particleTexture) {
  52811. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52812. }
  52813. return result;
  52814. };
  52815. /**
  52816. * Serializes the particle system to a JSON object.
  52817. * @returns the JSON object
  52818. */
  52819. GPUParticleSystem.prototype.serialize = function () {
  52820. var serializationObject = {};
  52821. serializationObject.name = this.name;
  52822. serializationObject.id = this.id;
  52823. // Emitter
  52824. if (this.emitter.position) {
  52825. var emitterMesh = this.emitter;
  52826. serializationObject.emitterId = emitterMesh.id;
  52827. }
  52828. else {
  52829. var emitterPosition = this.emitter;
  52830. serializationObject.emitter = emitterPosition.asArray();
  52831. }
  52832. serializationObject.capacity = this.getCapacity();
  52833. if (this.particleTexture) {
  52834. serializationObject.textureName = this.particleTexture.name;
  52835. }
  52836. // Animations
  52837. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52838. // Particle system
  52839. serializationObject.activeParticleCount = this.activeParticleCount;
  52840. serializationObject.randomTextureSize = this._randomTextureSize;
  52841. serializationObject.minSize = this.minSize;
  52842. serializationObject.maxSize = this.maxSize;
  52843. serializationObject.minEmitPower = this.minEmitPower;
  52844. serializationObject.maxEmitPower = this.maxEmitPower;
  52845. serializationObject.minLifeTime = this.minLifeTime;
  52846. serializationObject.maxLifeTime = this.maxLifeTime;
  52847. serializationObject.emitRate = this.emitRate;
  52848. serializationObject.gravity = this.gravity.asArray();
  52849. serializationObject.color1 = this.color1.asArray();
  52850. serializationObject.color2 = this.color2.asArray();
  52851. serializationObject.colorDead = this.colorDead.asArray();
  52852. serializationObject.updateSpeed = this.updateSpeed;
  52853. serializationObject.targetStopDuration = this.targetStopDuration;
  52854. serializationObject.blendMode = this.blendMode;
  52855. // Emitter
  52856. if (this.particleEmitterType) {
  52857. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52858. }
  52859. return serializationObject;
  52860. };
  52861. /**
  52862. * Parses a JSON object to create a GPU particle system.
  52863. * @param parsedParticleSystem The JSON object to parse
  52864. * @param scene The scene to create the particle system in
  52865. * @param rootUrl The root url to use to load external dependencies like texture
  52866. * @returns the parsed GPU particle system
  52867. */
  52868. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52869. var name = parsedParticleSystem.name;
  52870. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  52871. if (parsedParticleSystem.id) {
  52872. particleSystem.id = parsedParticleSystem.id;
  52873. }
  52874. // Texture
  52875. if (parsedParticleSystem.textureName) {
  52876. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52877. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52878. }
  52879. // Emitter
  52880. if (parsedParticleSystem.emitterId) {
  52881. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52882. }
  52883. else {
  52884. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52885. }
  52886. // Animations
  52887. if (parsedParticleSystem.animations) {
  52888. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52889. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52890. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52891. }
  52892. }
  52893. // Particle system
  52894. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  52895. particleSystem.minSize = parsedParticleSystem.minSize;
  52896. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52897. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52898. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52899. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52900. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52901. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52902. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52903. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52904. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52905. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52906. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52907. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52908. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52909. // Emitter
  52910. if (parsedParticleSystem.particleEmitterType) {
  52911. var emitterType = void 0;
  52912. switch (parsedParticleSystem.particleEmitterType.type) {
  52913. case "SphereEmitter":
  52914. emitterType = new BABYLON.SphereParticleEmitter();
  52915. break;
  52916. case "SphereDirectedParticleEmitter":
  52917. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  52918. break;
  52919. case "ConeEmitter":
  52920. emitterType = new BABYLON.ConeParticleEmitter();
  52921. break;
  52922. case "BoxEmitter":
  52923. default:
  52924. emitterType = new BABYLON.BoxParticleEmitter();
  52925. break;
  52926. }
  52927. emitterType.parse(parsedParticleSystem.particleEmitterType);
  52928. particleSystem.particleEmitterType = emitterType;
  52929. }
  52930. return particleSystem;
  52931. };
  52932. return GPUParticleSystem;
  52933. }());
  52934. BABYLON.GPUParticleSystem = GPUParticleSystem;
  52935. })(BABYLON || (BABYLON = {}));
  52936. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  52937. var BABYLON;
  52938. (function (BABYLON) {
  52939. /**
  52940. * Represents one particle of a solid particle system.
  52941. * @see SolidParticleSystem
  52942. */
  52943. var SolidParticle = /** @class */ (function () {
  52944. /**
  52945. * Creates a Solid Particle object.
  52946. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52947. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52948. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52949. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52950. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52951. * @param shapeId (integer) is the model shape identifier in the SPS.
  52952. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52953. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52954. */
  52955. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52956. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52957. /**
  52958. * particle global index
  52959. */
  52960. this.idx = 0;
  52961. /**
  52962. * The color of the particle
  52963. */
  52964. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52965. /**
  52966. * The world space position of the particle.
  52967. */
  52968. this.position = BABYLON.Vector3.Zero();
  52969. /**
  52970. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52971. */
  52972. this.rotation = BABYLON.Vector3.Zero();
  52973. /**
  52974. * The scaling of the particle.
  52975. */
  52976. this.scaling = BABYLON.Vector3.One();
  52977. /**
  52978. * The uvs of the particle.
  52979. */
  52980. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52981. /**
  52982. * The current speed of the particle.
  52983. */
  52984. this.velocity = BABYLON.Vector3.Zero();
  52985. /**
  52986. * The pivot point in the particle local space.
  52987. */
  52988. this.pivot = BABYLON.Vector3.Zero();
  52989. /**
  52990. * Must the particle be translated from its pivot point in its local space ?
  52991. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52992. * Default : false
  52993. */
  52994. this.translateFromPivot = false;
  52995. /**
  52996. * Is the particle active or not ?
  52997. */
  52998. this.alive = true;
  52999. /**
  53000. * Is the particle visible or not ?
  53001. */
  53002. this.isVisible = true;
  53003. /**
  53004. * Index of this particle in the global "positions" array (Internal use)
  53005. */
  53006. this._pos = 0;
  53007. /**
  53008. * Index of this particle in the global "indices" array (Internal use)
  53009. */
  53010. this._ind = 0;
  53011. /**
  53012. * ModelShape id of this particle
  53013. */
  53014. this.shapeId = 0;
  53015. /**
  53016. * Index of the particle in its shape id (Internal use)
  53017. */
  53018. this.idxInShape = 0;
  53019. /**
  53020. * Still set as invisible in order to skip useless computations (Internal use)
  53021. */
  53022. this._stillInvisible = false;
  53023. /**
  53024. * Last computed particle rotation matrix
  53025. */
  53026. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53027. /**
  53028. * Parent particle Id, if any.
  53029. * Default null.
  53030. */
  53031. this.parentId = null;
  53032. /**
  53033. * Internal global position in the SPS.
  53034. */
  53035. this._globalPosition = BABYLON.Vector3.Zero();
  53036. this.idx = particleIndex;
  53037. this._pos = positionIndex;
  53038. this._ind = indiceIndex;
  53039. this._model = model;
  53040. this.shapeId = shapeId;
  53041. this.idxInShape = idxInShape;
  53042. this._sps = sps;
  53043. if (modelBoundingInfo) {
  53044. this._modelBoundingInfo = modelBoundingInfo;
  53045. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53046. }
  53047. }
  53048. Object.defineProperty(SolidParticle.prototype, "scale", {
  53049. /**
  53050. * Legacy support, changed scale to scaling
  53051. */
  53052. get: function () {
  53053. return this.scaling;
  53054. },
  53055. /**
  53056. * Legacy support, changed scale to scaling
  53057. */
  53058. set: function (scale) {
  53059. this.scaling = scale;
  53060. },
  53061. enumerable: true,
  53062. configurable: true
  53063. });
  53064. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53065. /**
  53066. * Legacy support, changed quaternion to rotationQuaternion
  53067. */
  53068. get: function () {
  53069. return this.rotationQuaternion;
  53070. },
  53071. /**
  53072. * Legacy support, changed quaternion to rotationQuaternion
  53073. */
  53074. set: function (q) {
  53075. this.rotationQuaternion = q;
  53076. },
  53077. enumerable: true,
  53078. configurable: true
  53079. });
  53080. /**
  53081. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53082. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53083. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53084. * @returns true if it intersects
  53085. */
  53086. SolidParticle.prototype.intersectsMesh = function (target) {
  53087. if (!this._boundingInfo || !target._boundingInfo) {
  53088. return false;
  53089. }
  53090. if (this._sps._bSphereOnly) {
  53091. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53092. }
  53093. return this._boundingInfo.intersects(target._boundingInfo, false);
  53094. };
  53095. return SolidParticle;
  53096. }());
  53097. BABYLON.SolidParticle = SolidParticle;
  53098. /**
  53099. * Represents the shape of the model used by one particle of a solid particle system.
  53100. * SPS internal tool, don't use it manually.
  53101. * @see SolidParticleSystem
  53102. */
  53103. var ModelShape = /** @class */ (function () {
  53104. /**
  53105. * 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.
  53106. * SPS internal tool, don't use it manually.
  53107. * @ignore
  53108. */
  53109. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53110. /**
  53111. * length of the shape in the model indices array (internal use)
  53112. */
  53113. this._indicesLength = 0;
  53114. this.shapeID = id;
  53115. this._shape = shape;
  53116. this._indicesLength = indicesLength;
  53117. this._shapeUV = shapeUV;
  53118. this._positionFunction = posFunction;
  53119. this._vertexFunction = vtxFunction;
  53120. }
  53121. return ModelShape;
  53122. }());
  53123. BABYLON.ModelShape = ModelShape;
  53124. /**
  53125. * Represents a Depth Sorted Particle in the solid particle system.
  53126. * @see SolidParticleSystem
  53127. */
  53128. var DepthSortedParticle = /** @class */ (function () {
  53129. function DepthSortedParticle() {
  53130. /**
  53131. * Index of the particle in the "indices" array
  53132. */
  53133. this.ind = 0;
  53134. /**
  53135. * Length of the particle shape in the "indices" array
  53136. */
  53137. this.indicesLength = 0;
  53138. /**
  53139. * Squared distance from the particle to the camera
  53140. */
  53141. this.sqDistance = 0.0;
  53142. }
  53143. return DepthSortedParticle;
  53144. }());
  53145. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53146. })(BABYLON || (BABYLON = {}));
  53147. //# sourceMappingURL=babylon.solidParticle.js.map
  53148. var BABYLON;
  53149. (function (BABYLON) {
  53150. /**
  53151. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53152. *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.
  53153. * The SPS is also a particle system. It provides some methods to manage the particles.
  53154. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53155. *
  53156. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53157. */
  53158. var SolidParticleSystem = /** @class */ (function () {
  53159. /**
  53160. * Creates a SPS (Solid Particle System) object.
  53161. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53162. * @param scene (Scene) is the scene in which the SPS is added.
  53163. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53164. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53165. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53166. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53167. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53168. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53169. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53170. */
  53171. function SolidParticleSystem(name, scene, options) {
  53172. /**
  53173. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53174. * Example : var p = SPS.particles[i];
  53175. */
  53176. this.particles = new Array();
  53177. /**
  53178. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53179. */
  53180. this.nbParticles = 0;
  53181. /**
  53182. * If the particles must ever face the camera (default false). Useful for planar particles.
  53183. */
  53184. this.billboard = false;
  53185. /**
  53186. * Recompute normals when adding a shape
  53187. */
  53188. this.recomputeNormals = true;
  53189. /**
  53190. * This a counter ofr your own usage. It's not set by any SPS functions.
  53191. */
  53192. this.counter = 0;
  53193. /**
  53194. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53195. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53196. */
  53197. this.vars = {};
  53198. /**
  53199. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53200. */
  53201. this._bSphereOnly = false;
  53202. /**
  53203. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53204. */
  53205. this._bSphereRadiusFactor = 1.0;
  53206. this._positions = new Array();
  53207. this._indices = new Array();
  53208. this._normals = new Array();
  53209. this._colors = new Array();
  53210. this._uvs = new Array();
  53211. this._index = 0; // indices index
  53212. this._updatable = true;
  53213. this._pickable = false;
  53214. this._isVisibilityBoxLocked = false;
  53215. this._alwaysVisible = false;
  53216. this._depthSort = false;
  53217. this._shapeCounter = 0;
  53218. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53219. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53220. this._computeParticleColor = true;
  53221. this._computeParticleTexture = true;
  53222. this._computeParticleRotation = true;
  53223. this._computeParticleVertex = false;
  53224. this._computeBoundingBox = false;
  53225. this._depthSortParticles = true;
  53226. this._cam_axisZ = BABYLON.Vector3.Zero();
  53227. this._cam_axisY = BABYLON.Vector3.Zero();
  53228. this._cam_axisX = BABYLON.Vector3.Zero();
  53229. this._axisZ = BABYLON.Axis.Z;
  53230. this._camDir = BABYLON.Vector3.Zero();
  53231. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53232. this._rotMatrix = new BABYLON.Matrix();
  53233. this._invertMatrix = new BABYLON.Matrix();
  53234. this._rotated = BABYLON.Vector3.Zero();
  53235. this._quaternion = new BABYLON.Quaternion();
  53236. this._vertex = BABYLON.Vector3.Zero();
  53237. this._normal = BABYLON.Vector3.Zero();
  53238. this._yaw = 0.0;
  53239. this._pitch = 0.0;
  53240. this._roll = 0.0;
  53241. this._halfroll = 0.0;
  53242. this._halfpitch = 0.0;
  53243. this._halfyaw = 0.0;
  53244. this._sinRoll = 0.0;
  53245. this._cosRoll = 0.0;
  53246. this._sinPitch = 0.0;
  53247. this._cosPitch = 0.0;
  53248. this._sinYaw = 0.0;
  53249. this._cosYaw = 0.0;
  53250. this._mustUnrotateFixedNormals = false;
  53251. this._minimum = BABYLON.Vector3.Zero();
  53252. this._maximum = BABYLON.Vector3.Zero();
  53253. this._minBbox = BABYLON.Vector3.Zero();
  53254. this._maxBbox = BABYLON.Vector3.Zero();
  53255. this._particlesIntersect = false;
  53256. this._depthSortFunction = function (p1, p2) {
  53257. return (p2.sqDistance - p1.sqDistance);
  53258. };
  53259. this._needs32Bits = false;
  53260. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53261. this._scaledPivot = BABYLON.Vector3.Zero();
  53262. this._particleHasParent = false;
  53263. this.name = name;
  53264. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53265. this._camera = scene.activeCamera;
  53266. this._pickable = options ? options.isPickable : false;
  53267. this._depthSort = options ? options.enableDepthSort : false;
  53268. this._particlesIntersect = options ? options.particleIntersection : false;
  53269. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53270. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53271. if (options && options.updatable) {
  53272. this._updatable = options.updatable;
  53273. }
  53274. else {
  53275. this._updatable = true;
  53276. }
  53277. if (this._pickable) {
  53278. this.pickedParticles = [];
  53279. }
  53280. if (this._depthSort) {
  53281. this.depthSortedParticles = [];
  53282. }
  53283. }
  53284. /**
  53285. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53286. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53287. * @returns the created mesh
  53288. */
  53289. SolidParticleSystem.prototype.buildMesh = function () {
  53290. if (this.nbParticles === 0) {
  53291. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53292. this.addShape(triangle, 1);
  53293. triangle.dispose();
  53294. }
  53295. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53296. this._positions32 = new Float32Array(this._positions);
  53297. this._uvs32 = new Float32Array(this._uvs);
  53298. this._colors32 = new Float32Array(this._colors);
  53299. if (this.recomputeNormals) {
  53300. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53301. }
  53302. this._normals32 = new Float32Array(this._normals);
  53303. this._fixedNormal32 = new Float32Array(this._normals);
  53304. if (this._mustUnrotateFixedNormals) {
  53305. this._unrotateFixedNormals();
  53306. }
  53307. var vertexData = new BABYLON.VertexData();
  53308. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53309. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53310. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53311. if (this._uvs32) {
  53312. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53313. ;
  53314. }
  53315. if (this._colors32) {
  53316. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53317. }
  53318. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53319. vertexData.applyToMesh(mesh, this._updatable);
  53320. this.mesh = mesh;
  53321. this.mesh.isPickable = this._pickable;
  53322. // free memory
  53323. if (!this._depthSort) {
  53324. this._indices = null;
  53325. }
  53326. this._positions = null;
  53327. this._normals = null;
  53328. this._uvs = null;
  53329. this._colors = null;
  53330. if (!this._updatable) {
  53331. this.particles.length = 0;
  53332. }
  53333. return mesh;
  53334. };
  53335. /**
  53336. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53337. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53338. * Thus the particles generated from `digest()` have their property `position` set yet.
  53339. * @param mesh ( Mesh ) is the mesh to be digested
  53340. * @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
  53341. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53342. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53343. * @returns the current SPS
  53344. */
  53345. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53346. var size = (options && options.facetNb) || 1;
  53347. var number = (options && options.number) || 0;
  53348. var delta = (options && options.delta) || 0;
  53349. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53350. var meshInd = mesh.getIndices();
  53351. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53352. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53353. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53354. var f = 0; // facet counter
  53355. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53356. // compute size from number
  53357. if (number) {
  53358. number = (number > totalFacets) ? totalFacets : number;
  53359. size = Math.round(totalFacets / number);
  53360. delta = 0;
  53361. }
  53362. else {
  53363. size = (size > totalFacets) ? totalFacets : size;
  53364. }
  53365. var facetPos = []; // submesh positions
  53366. var facetInd = []; // submesh indices
  53367. var facetUV = []; // submesh UV
  53368. var facetCol = []; // submesh colors
  53369. var barycenter = BABYLON.Vector3.Zero();
  53370. var sizeO = size;
  53371. while (f < totalFacets) {
  53372. size = sizeO + Math.floor((1 + delta) * Math.random());
  53373. if (f > totalFacets - size) {
  53374. size = totalFacets - f;
  53375. }
  53376. // reset temp arrays
  53377. facetPos.length = 0;
  53378. facetInd.length = 0;
  53379. facetUV.length = 0;
  53380. facetCol.length = 0;
  53381. // iterate over "size" facets
  53382. var fi = 0;
  53383. for (var j = f * 3; j < (f + size) * 3; j++) {
  53384. facetInd.push(fi);
  53385. var i = meshInd[j];
  53386. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53387. if (meshUV) {
  53388. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53389. }
  53390. if (meshCol) {
  53391. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53392. }
  53393. fi++;
  53394. }
  53395. // create a model shape for each single particle
  53396. var idx = this.nbParticles;
  53397. var shape = this._posToShape(facetPos);
  53398. var shapeUV = this._uvsToShapeUV(facetUV);
  53399. // compute the barycenter of the shape
  53400. var v;
  53401. for (v = 0; v < shape.length; v++) {
  53402. barycenter.addInPlace(shape[v]);
  53403. }
  53404. barycenter.scaleInPlace(1 / shape.length);
  53405. // shift the shape from its barycenter to the origin
  53406. for (v = 0; v < shape.length; v++) {
  53407. shape[v].subtractInPlace(barycenter);
  53408. }
  53409. var bInfo;
  53410. if (this._particlesIntersect) {
  53411. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53412. }
  53413. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53414. // add the particle in the SPS
  53415. var currentPos = this._positions.length;
  53416. var currentInd = this._indices.length;
  53417. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53418. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53419. // initialize the particle position
  53420. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53421. this._index += shape.length;
  53422. idx++;
  53423. this.nbParticles++;
  53424. this._shapeCounter++;
  53425. f += size;
  53426. }
  53427. return this;
  53428. };
  53429. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53430. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53431. var index = 0;
  53432. var idx = 0;
  53433. for (var p = 0; p < this.particles.length; p++) {
  53434. this._particle = this.particles[p];
  53435. this._shape = this._particle._model._shape;
  53436. if (this._particle.rotationQuaternion) {
  53437. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53438. }
  53439. else {
  53440. this._yaw = this._particle.rotation.y;
  53441. this._pitch = this._particle.rotation.x;
  53442. this._roll = this._particle.rotation.z;
  53443. this._quaternionRotationYPR();
  53444. }
  53445. this._quaternionToRotationMatrix();
  53446. this._rotMatrix.invertToRef(this._invertMatrix);
  53447. for (var pt = 0; pt < this._shape.length; pt++) {
  53448. idx = index + pt * 3;
  53449. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53450. this._fixedNormal32[idx] = this._normal.x;
  53451. this._fixedNormal32[idx + 1] = this._normal.y;
  53452. this._fixedNormal32[idx + 2] = this._normal.z;
  53453. }
  53454. index = idx + 3;
  53455. }
  53456. };
  53457. //reset copy
  53458. SolidParticleSystem.prototype._resetCopy = function () {
  53459. this._copy.position.x = 0;
  53460. this._copy.position.y = 0;
  53461. this._copy.position.z = 0;
  53462. this._copy.rotation.x = 0;
  53463. this._copy.rotation.y = 0;
  53464. this._copy.rotation.z = 0;
  53465. this._copy.rotationQuaternion = null;
  53466. this._copy.scaling.x = 1.0;
  53467. this._copy.scaling.y = 1.0;
  53468. this._copy.scaling.z = 1.0;
  53469. this._copy.uvs.x = 0;
  53470. this._copy.uvs.y = 0;
  53471. this._copy.uvs.z = 1.0;
  53472. this._copy.uvs.w = 1.0;
  53473. this._copy.color = null;
  53474. this._copy.translateFromPivot = false;
  53475. };
  53476. // _meshBuilder : inserts the shape model in the global SPS mesh
  53477. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53478. var i;
  53479. var u = 0;
  53480. var c = 0;
  53481. var n = 0;
  53482. this._resetCopy();
  53483. if (options && options.positionFunction) {
  53484. options.positionFunction(this._copy, idx, idxInShape);
  53485. this._mustUnrotateFixedNormals = true;
  53486. }
  53487. if (this._copy.rotationQuaternion) {
  53488. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53489. }
  53490. else {
  53491. this._yaw = this._copy.rotation.y;
  53492. this._pitch = this._copy.rotation.x;
  53493. this._roll = this._copy.rotation.z;
  53494. this._quaternionRotationYPR();
  53495. }
  53496. this._quaternionToRotationMatrix();
  53497. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53498. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53499. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53500. if (this._copy.translateFromPivot) {
  53501. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53502. }
  53503. else {
  53504. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53505. }
  53506. for (i = 0; i < shape.length; i++) {
  53507. this._vertex.x = shape[i].x;
  53508. this._vertex.y = shape[i].y;
  53509. this._vertex.z = shape[i].z;
  53510. if (options && options.vertexFunction) {
  53511. options.vertexFunction(this._copy, this._vertex, i);
  53512. }
  53513. this._vertex.x *= this._copy.scaling.x;
  53514. this._vertex.y *= this._copy.scaling.y;
  53515. this._vertex.z *= this._copy.scaling.z;
  53516. this._vertex.x -= this._scaledPivot.x;
  53517. this._vertex.y -= this._scaledPivot.y;
  53518. this._vertex.z -= this._scaledPivot.z;
  53519. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53520. this._rotated.addInPlace(this._pivotBackTranslation);
  53521. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53522. if (meshUV) {
  53523. 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);
  53524. u += 2;
  53525. }
  53526. if (this._copy.color) {
  53527. this._color = this._copy.color;
  53528. }
  53529. else if (meshCol && meshCol[c] !== undefined) {
  53530. this._color.r = meshCol[c];
  53531. this._color.g = meshCol[c + 1];
  53532. this._color.b = meshCol[c + 2];
  53533. this._color.a = meshCol[c + 3];
  53534. }
  53535. else {
  53536. this._color.r = 1.0;
  53537. this._color.g = 1.0;
  53538. this._color.b = 1.0;
  53539. this._color.a = 1.0;
  53540. }
  53541. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53542. c += 4;
  53543. if (!this.recomputeNormals && meshNor) {
  53544. this._normal.x = meshNor[n];
  53545. this._normal.y = meshNor[n + 1];
  53546. this._normal.z = meshNor[n + 2];
  53547. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53548. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53549. n += 3;
  53550. }
  53551. }
  53552. for (i = 0; i < meshInd.length; i++) {
  53553. var current_ind = p + meshInd[i];
  53554. indices.push(current_ind);
  53555. if (current_ind > 65535) {
  53556. this._needs32Bits = true;
  53557. }
  53558. }
  53559. if (this._pickable) {
  53560. var nbfaces = meshInd.length / 3;
  53561. for (i = 0; i < nbfaces; i++) {
  53562. this.pickedParticles.push({ idx: idx, faceId: i });
  53563. }
  53564. }
  53565. if (this._depthSort) {
  53566. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  53567. }
  53568. return this._copy;
  53569. };
  53570. // returns a shape array from positions array
  53571. SolidParticleSystem.prototype._posToShape = function (positions) {
  53572. var shape = [];
  53573. for (var i = 0; i < positions.length; i += 3) {
  53574. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53575. }
  53576. return shape;
  53577. };
  53578. // returns a shapeUV array from a Vector4 uvs
  53579. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53580. var shapeUV = [];
  53581. if (uvs) {
  53582. for (var i = 0; i < uvs.length; i++)
  53583. shapeUV.push(uvs[i]);
  53584. }
  53585. return shapeUV;
  53586. };
  53587. // adds a new particle object in the particles array
  53588. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  53589. if (bInfo === void 0) { bInfo = null; }
  53590. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  53591. this.particles.push(sp);
  53592. return sp;
  53593. };
  53594. /**
  53595. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53596. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53597. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  53598. * @param nb (positive integer) the number of particles to be created from this model
  53599. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  53600. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  53601. * @returns the number of shapes in the system
  53602. */
  53603. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53604. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53605. var meshInd = mesh.getIndices();
  53606. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53607. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53608. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53609. var bbInfo;
  53610. if (this._particlesIntersect) {
  53611. bbInfo = mesh.getBoundingInfo();
  53612. }
  53613. var shape = this._posToShape(meshPos);
  53614. var shapeUV = this._uvsToShapeUV(meshUV);
  53615. var posfunc = options ? options.positionFunction : null;
  53616. var vtxfunc = options ? options.vertexFunction : null;
  53617. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  53618. // particles
  53619. var sp;
  53620. var currentCopy;
  53621. var idx = this.nbParticles;
  53622. for (var i = 0; i < nb; i++) {
  53623. var currentPos = this._positions.length;
  53624. var currentInd = this._indices.length;
  53625. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53626. if (this._updatable) {
  53627. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  53628. sp.position.copyFrom(currentCopy.position);
  53629. sp.rotation.copyFrom(currentCopy.rotation);
  53630. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  53631. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53632. }
  53633. if (currentCopy.color && sp.color) {
  53634. sp.color.copyFrom(currentCopy.color);
  53635. }
  53636. sp.scaling.copyFrom(currentCopy.scaling);
  53637. sp.uvs.copyFrom(currentCopy.uvs);
  53638. }
  53639. this._index += shape.length;
  53640. idx++;
  53641. }
  53642. this.nbParticles += nb;
  53643. this._shapeCounter++;
  53644. return this._shapeCounter - 1;
  53645. };
  53646. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53647. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53648. this._resetCopy();
  53649. if (particle._model._positionFunction) {
  53650. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53651. }
  53652. if (this._copy.rotationQuaternion) {
  53653. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53654. }
  53655. else {
  53656. this._yaw = this._copy.rotation.y;
  53657. this._pitch = this._copy.rotation.x;
  53658. this._roll = this._copy.rotation.z;
  53659. this._quaternionRotationYPR();
  53660. }
  53661. this._quaternionToRotationMatrix();
  53662. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53663. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53664. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53665. if (this._copy.translateFromPivot) {
  53666. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53667. }
  53668. else {
  53669. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53670. }
  53671. this._shape = particle._model._shape;
  53672. for (var pt = 0; pt < this._shape.length; pt++) {
  53673. this._vertex.x = this._shape[pt].x;
  53674. this._vertex.y = this._shape[pt].y;
  53675. this._vertex.z = this._shape[pt].z;
  53676. if (particle._model._vertexFunction) {
  53677. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53678. }
  53679. this._vertex.x *= this._copy.scaling.x;
  53680. this._vertex.y *= this._copy.scaling.y;
  53681. this._vertex.z *= this._copy.scaling.z;
  53682. this._vertex.x -= this._scaledPivot.x;
  53683. this._vertex.y -= this._scaledPivot.y;
  53684. this._vertex.z -= this._scaledPivot.z;
  53685. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53686. this._rotated.addInPlace(this._pivotBackTranslation);
  53687. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53688. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53689. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53690. }
  53691. particle.position.x = 0.0;
  53692. particle.position.y = 0.0;
  53693. particle.position.z = 0.0;
  53694. particle.rotation.x = 0.0;
  53695. particle.rotation.y = 0.0;
  53696. particle.rotation.z = 0.0;
  53697. particle.rotationQuaternion = null;
  53698. particle.scaling.x = 1.0;
  53699. particle.scaling.y = 1.0;
  53700. particle.scaling.z = 1.0;
  53701. particle.uvs.x = 0.0;
  53702. particle.uvs.y = 0.0;
  53703. particle.uvs.z = 1.0;
  53704. particle.uvs.w = 1.0;
  53705. particle.pivot.x = 0.0;
  53706. particle.pivot.y = 0.0;
  53707. particle.pivot.z = 0.0;
  53708. particle.translateFromPivot = false;
  53709. particle.parentId = null;
  53710. };
  53711. /**
  53712. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53713. * @returns the SPS.
  53714. */
  53715. SolidParticleSystem.prototype.rebuildMesh = function () {
  53716. for (var p = 0; p < this.particles.length; p++) {
  53717. this._rebuildParticle(this.particles[p]);
  53718. }
  53719. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53720. return this;
  53721. };
  53722. /**
  53723. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53724. * This method calls `updateParticle()` for each particle of the SPS.
  53725. * For an animated SPS, it is usually called within the render loop.
  53726. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53727. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53728. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53729. * @returns the SPS.
  53730. */
  53731. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53732. if (start === void 0) { start = 0; }
  53733. if (end === void 0) { end = this.nbParticles - 1; }
  53734. if (update === void 0) { update = true; }
  53735. if (!this._updatable) {
  53736. return this;
  53737. }
  53738. // custom beforeUpdate
  53739. this.beforeUpdateParticles(start, end, update);
  53740. this._cam_axisX.x = 1.0;
  53741. this._cam_axisX.y = 0.0;
  53742. this._cam_axisX.z = 0.0;
  53743. this._cam_axisY.x = 0.0;
  53744. this._cam_axisY.y = 1.0;
  53745. this._cam_axisY.z = 0.0;
  53746. this._cam_axisZ.x = 0.0;
  53747. this._cam_axisZ.y = 0.0;
  53748. this._cam_axisZ.z = 1.0;
  53749. // cases when the World Matrix is to be computed first
  53750. if (this.billboard || this._depthSort) {
  53751. this.mesh.computeWorldMatrix(true);
  53752. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53753. }
  53754. // if the particles will always face the camera
  53755. if (this.billboard) {
  53756. // compute the camera position and un-rotate it by the current mesh rotation
  53757. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53758. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53759. this._cam_axisZ.normalize();
  53760. // same for camera up vector extracted from the cam view matrix
  53761. var view = this._camera.getViewMatrix(true);
  53762. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53763. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53764. this._cam_axisY.normalize();
  53765. this._cam_axisX.normalize();
  53766. }
  53767. // if depthSort, compute the camera global position in the mesh local system
  53768. if (this._depthSort) {
  53769. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53770. }
  53771. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53772. var idx = 0; // current position index in the global array positions32
  53773. var index = 0; // position start index in the global array positions32 of the current particle
  53774. var colidx = 0; // current color index in the global array colors32
  53775. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53776. var uvidx = 0; // current uv index in the global array uvs32
  53777. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53778. var pt = 0; // current index in the particle model shape
  53779. if (this.mesh.isFacetDataEnabled) {
  53780. this._computeBoundingBox = true;
  53781. }
  53782. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53783. if (this._computeBoundingBox) {
  53784. if (start == 0 && end == this.nbParticles - 1) {
  53785. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53786. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53787. }
  53788. else {
  53789. if (this.mesh._boundingInfo) {
  53790. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53791. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53792. }
  53793. }
  53794. }
  53795. // particle loop
  53796. index = this.particles[start]._pos;
  53797. var vpos = (index / 3) | 0;
  53798. colorIndex = vpos * 4;
  53799. uvIndex = vpos * 2;
  53800. for (var p = start; p <= end; p++) {
  53801. this._particle = this.particles[p];
  53802. this._shape = this._particle._model._shape;
  53803. this._shapeUV = this._particle._model._shapeUV;
  53804. // call to custom user function to update the particle properties
  53805. this.updateParticle(this._particle);
  53806. // camera-particle distance for depth sorting
  53807. if (this._depthSort && this._depthSortParticles) {
  53808. var dsp = this.depthSortedParticles[p];
  53809. dsp.ind = this._particle._ind;
  53810. dsp.indicesLength = this._particle._model._indicesLength;
  53811. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53812. }
  53813. // skip the computations for inactive or already invisible particles
  53814. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53815. // increment indexes for the next particle
  53816. pt = this._shape.length;
  53817. index += pt * 3;
  53818. colorIndex += pt * 4;
  53819. uvIndex += pt * 2;
  53820. continue;
  53821. }
  53822. if (this._particle.isVisible) {
  53823. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53824. this._particleHasParent = (this._particle.parentId !== null);
  53825. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53826. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53827. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53828. // particle rotation matrix
  53829. if (this.billboard) {
  53830. this._particle.rotation.x = 0.0;
  53831. this._particle.rotation.y = 0.0;
  53832. }
  53833. if (this._computeParticleRotation || this.billboard) {
  53834. if (this._particle.rotationQuaternion) {
  53835. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53836. }
  53837. else {
  53838. this._yaw = this._particle.rotation.y;
  53839. this._pitch = this._particle.rotation.x;
  53840. this._roll = this._particle.rotation.z;
  53841. this._quaternionRotationYPR();
  53842. }
  53843. this._quaternionToRotationMatrix();
  53844. }
  53845. if (this._particleHasParent) {
  53846. this._parent = this.particles[this._particle.parentId];
  53847. 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];
  53848. 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];
  53849. 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];
  53850. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53851. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53852. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53853. if (this._computeParticleRotation || this.billboard) {
  53854. 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];
  53855. 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];
  53856. 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];
  53857. 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];
  53858. 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];
  53859. 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];
  53860. 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];
  53861. 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];
  53862. 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];
  53863. }
  53864. }
  53865. else {
  53866. this._particle._globalPosition.x = this._particle.position.x;
  53867. this._particle._globalPosition.y = this._particle.position.y;
  53868. this._particle._globalPosition.z = this._particle.position.z;
  53869. if (this._computeParticleRotation || this.billboard) {
  53870. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53871. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53872. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53873. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53874. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53875. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53876. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53877. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53878. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53879. }
  53880. }
  53881. if (this._particle.translateFromPivot) {
  53882. this._pivotBackTranslation.x = 0.0;
  53883. this._pivotBackTranslation.y = 0.0;
  53884. this._pivotBackTranslation.z = 0.0;
  53885. }
  53886. else {
  53887. this._pivotBackTranslation.x = this._scaledPivot.x;
  53888. this._pivotBackTranslation.y = this._scaledPivot.y;
  53889. this._pivotBackTranslation.z = this._scaledPivot.z;
  53890. }
  53891. // particle vertex loop
  53892. for (pt = 0; pt < this._shape.length; pt++) {
  53893. idx = index + pt * 3;
  53894. colidx = colorIndex + pt * 4;
  53895. uvidx = uvIndex + pt * 2;
  53896. this._vertex.x = this._shape[pt].x;
  53897. this._vertex.y = this._shape[pt].y;
  53898. this._vertex.z = this._shape[pt].z;
  53899. if (this._computeParticleVertex) {
  53900. this.updateParticleVertex(this._particle, this._vertex, pt);
  53901. }
  53902. // positions
  53903. this._vertex.x *= this._particle.scaling.x;
  53904. this._vertex.y *= this._particle.scaling.y;
  53905. this._vertex.z *= this._particle.scaling.z;
  53906. this._vertex.x -= this._scaledPivot.x;
  53907. this._vertex.y -= this._scaledPivot.y;
  53908. this._vertex.z -= this._scaledPivot.z;
  53909. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53910. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53911. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53912. this._rotated.x += this._pivotBackTranslation.x;
  53913. this._rotated.y += this._pivotBackTranslation.y;
  53914. this._rotated.z += this._pivotBackTranslation.z;
  53915. 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;
  53916. 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;
  53917. 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;
  53918. if (this._computeBoundingBox) {
  53919. if (this._positions32[idx] < this._minimum.x) {
  53920. this._minimum.x = this._positions32[idx];
  53921. }
  53922. if (this._positions32[idx] > this._maximum.x) {
  53923. this._maximum.x = this._positions32[idx];
  53924. }
  53925. if (this._positions32[idx + 1] < this._minimum.y) {
  53926. this._minimum.y = this._positions32[idx + 1];
  53927. }
  53928. if (this._positions32[idx + 1] > this._maximum.y) {
  53929. this._maximum.y = this._positions32[idx + 1];
  53930. }
  53931. if (this._positions32[idx + 2] < this._minimum.z) {
  53932. this._minimum.z = this._positions32[idx + 2];
  53933. }
  53934. if (this._positions32[idx + 2] > this._maximum.z) {
  53935. this._maximum.z = this._positions32[idx + 2];
  53936. }
  53937. }
  53938. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53939. if (!this._computeParticleVertex) {
  53940. this._normal.x = this._fixedNormal32[idx];
  53941. this._normal.y = this._fixedNormal32[idx + 1];
  53942. this._normal.z = this._fixedNormal32[idx + 2];
  53943. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53944. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53945. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53946. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53947. 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;
  53948. 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;
  53949. }
  53950. if (this._computeParticleColor && this._particle.color) {
  53951. this._colors32[colidx] = this._particle.color.r;
  53952. this._colors32[colidx + 1] = this._particle.color.g;
  53953. this._colors32[colidx + 2] = this._particle.color.b;
  53954. this._colors32[colidx + 3] = this._particle.color.a;
  53955. }
  53956. if (this._computeParticleTexture) {
  53957. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53958. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53959. }
  53960. }
  53961. }
  53962. else {
  53963. this._particle._stillInvisible = true; // mark the particle as invisible
  53964. for (pt = 0; pt < this._shape.length; pt++) {
  53965. idx = index + pt * 3;
  53966. colidx = colorIndex + pt * 4;
  53967. uvidx = uvIndex + pt * 2;
  53968. this._positions32[idx] = 0.0;
  53969. this._positions32[idx + 1] = 0.0;
  53970. this._positions32[idx + 2] = 0.0;
  53971. this._normals32[idx] = 0.0;
  53972. this._normals32[idx + 1] = 0.0;
  53973. this._normals32[idx + 2] = 0.0;
  53974. if (this._computeParticleColor && this._particle.color) {
  53975. this._colors32[colidx] = this._particle.color.r;
  53976. this._colors32[colidx + 1] = this._particle.color.g;
  53977. this._colors32[colidx + 2] = this._particle.color.b;
  53978. this._colors32[colidx + 3] = this._particle.color.a;
  53979. }
  53980. if (this._computeParticleTexture) {
  53981. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53982. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53983. }
  53984. }
  53985. }
  53986. // if the particle intersections must be computed : update the bbInfo
  53987. if (this._particlesIntersect) {
  53988. var bInfo = this._particle._boundingInfo;
  53989. var bBox = bInfo.boundingBox;
  53990. var bSphere = bInfo.boundingSphere;
  53991. if (!this._bSphereOnly) {
  53992. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53993. for (var b = 0; b < bBox.vectors.length; b++) {
  53994. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53995. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53996. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53997. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53998. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53999. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54000. 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;
  54001. 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;
  54002. 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;
  54003. }
  54004. bBox._update(this.mesh._worldMatrix);
  54005. }
  54006. // place and scale the particle bouding sphere in the SPS local system, then update it
  54007. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54008. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54009. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54010. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54011. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54012. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54013. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54014. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54015. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54016. 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));
  54017. bSphere._update(this.mesh._worldMatrix);
  54018. }
  54019. // increment indexes for the next particle
  54020. index = idx + 3;
  54021. colorIndex = colidx + 4;
  54022. uvIndex = uvidx + 2;
  54023. }
  54024. // if the VBO must be updated
  54025. if (update) {
  54026. if (this._computeParticleColor) {
  54027. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54028. }
  54029. if (this._computeParticleTexture) {
  54030. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54031. }
  54032. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54033. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54034. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54035. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54036. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54037. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54038. for (var i = 0; i < this._normals32.length; i++) {
  54039. this._fixedNormal32[i] = this._normals32[i];
  54040. }
  54041. }
  54042. if (!this.mesh.areNormalsFrozen) {
  54043. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54044. }
  54045. }
  54046. if (this._depthSort && this._depthSortParticles) {
  54047. this.depthSortedParticles.sort(this._depthSortFunction);
  54048. var dspl = this.depthSortedParticles.length;
  54049. var sorted = 0;
  54050. var lind = 0;
  54051. var sind = 0;
  54052. var sid = 0;
  54053. for (sorted = 0; sorted < dspl; sorted++) {
  54054. lind = this.depthSortedParticles[sorted].indicesLength;
  54055. sind = this.depthSortedParticles[sorted].ind;
  54056. for (var i = 0; i < lind; i++) {
  54057. this._indices32[sid] = this._indices[sind + i];
  54058. sid++;
  54059. }
  54060. }
  54061. this.mesh.updateIndices(this._indices32);
  54062. }
  54063. }
  54064. if (this._computeBoundingBox) {
  54065. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54066. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54067. }
  54068. this.afterUpdateParticles(start, end, update);
  54069. return this;
  54070. };
  54071. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54072. this._halfroll = this._roll * 0.5;
  54073. this._halfpitch = this._pitch * 0.5;
  54074. this._halfyaw = this._yaw * 0.5;
  54075. this._sinRoll = Math.sin(this._halfroll);
  54076. this._cosRoll = Math.cos(this._halfroll);
  54077. this._sinPitch = Math.sin(this._halfpitch);
  54078. this._cosPitch = Math.cos(this._halfpitch);
  54079. this._sinYaw = Math.sin(this._halfyaw);
  54080. this._cosYaw = Math.cos(this._halfyaw);
  54081. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54082. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54083. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54084. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54085. };
  54086. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54087. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54088. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54089. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54090. this._rotMatrix.m[3] = 0;
  54091. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54092. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54093. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54094. this._rotMatrix.m[7] = 0;
  54095. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54096. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54097. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54098. this._rotMatrix.m[11] = 0;
  54099. this._rotMatrix.m[12] = 0;
  54100. this._rotMatrix.m[13] = 0;
  54101. this._rotMatrix.m[14] = 0;
  54102. this._rotMatrix.m[15] = 1.0;
  54103. };
  54104. /**
  54105. * Disposes the SPS.
  54106. */
  54107. SolidParticleSystem.prototype.dispose = function () {
  54108. this.mesh.dispose();
  54109. this.vars = null;
  54110. // drop references to internal big arrays for the GC
  54111. this._positions = null;
  54112. this._indices = null;
  54113. this._normals = null;
  54114. this._uvs = null;
  54115. this._colors = null;
  54116. this._indices32 = null;
  54117. this._positions32 = null;
  54118. this._normals32 = null;
  54119. this._fixedNormal32 = null;
  54120. this._uvs32 = null;
  54121. this._colors32 = null;
  54122. this.pickedParticles = null;
  54123. };
  54124. /**
  54125. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54126. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54127. * @returns the SPS.
  54128. */
  54129. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54130. if (!this._isVisibilityBoxLocked) {
  54131. this.mesh.refreshBoundingInfo();
  54132. }
  54133. return this;
  54134. };
  54135. /**
  54136. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54137. * @param size the size (float) of the visibility box
  54138. * note : this doesn't lock the SPS mesh bounding box.
  54139. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54140. */
  54141. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54142. var vis = size / 2;
  54143. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54144. };
  54145. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54146. /**
  54147. * Gets whether the SPS as always visible or not
  54148. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54149. */
  54150. get: function () {
  54151. return this._alwaysVisible;
  54152. },
  54153. /**
  54154. * Sets the SPS as always visible or not
  54155. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54156. */
  54157. set: function (val) {
  54158. this._alwaysVisible = val;
  54159. this.mesh.alwaysSelectAsActiveMesh = val;
  54160. },
  54161. enumerable: true,
  54162. configurable: true
  54163. });
  54164. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54165. /**
  54166. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54167. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54168. */
  54169. get: function () {
  54170. return this._isVisibilityBoxLocked;
  54171. },
  54172. /**
  54173. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54174. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54175. */
  54176. set: function (val) {
  54177. this._isVisibilityBoxLocked = val;
  54178. var boundingInfo = this.mesh.getBoundingInfo();
  54179. boundingInfo.isLocked = val;
  54180. },
  54181. enumerable: true,
  54182. configurable: true
  54183. });
  54184. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54185. /**
  54186. * Gets if `setParticles()` computes the particle rotations or not.
  54187. * Default value : true. The SPS is faster when it's set to false.
  54188. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54189. */
  54190. get: function () {
  54191. return this._computeParticleRotation;
  54192. },
  54193. /**
  54194. * Tells to `setParticles()` to compute the particle rotations or not.
  54195. * Default value : true. The SPS is faster when it's set to false.
  54196. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54197. */
  54198. set: function (val) {
  54199. this._computeParticleRotation = val;
  54200. },
  54201. enumerable: true,
  54202. configurable: true
  54203. });
  54204. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54205. /**
  54206. * Gets if `setParticles()` computes the particle colors or not.
  54207. * Default value : true. The SPS is faster when it's set to false.
  54208. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54209. */
  54210. get: function () {
  54211. return this._computeParticleColor;
  54212. },
  54213. /**
  54214. * Tells to `setParticles()` to compute the particle colors or not.
  54215. * Default value : true. The SPS is faster when it's set to false.
  54216. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54217. */
  54218. set: function (val) {
  54219. this._computeParticleColor = val;
  54220. },
  54221. enumerable: true,
  54222. configurable: true
  54223. });
  54224. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54225. /**
  54226. * Gets if `setParticles()` computes the particle textures or not.
  54227. * Default value : true. The SPS is faster when it's set to false.
  54228. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54229. */
  54230. get: function () {
  54231. return this._computeParticleTexture;
  54232. },
  54233. set: function (val) {
  54234. this._computeParticleTexture = val;
  54235. },
  54236. enumerable: true,
  54237. configurable: true
  54238. });
  54239. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54240. /**
  54241. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54242. * Default value : false. The SPS is faster when it's set to false.
  54243. * Note : the particle custom vertex positions aren't stored values.
  54244. */
  54245. get: function () {
  54246. return this._computeParticleVertex;
  54247. },
  54248. /**
  54249. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54250. * Default value : false. The SPS is faster when it's set to false.
  54251. * Note : the particle custom vertex positions aren't stored values.
  54252. */
  54253. set: function (val) {
  54254. this._computeParticleVertex = val;
  54255. },
  54256. enumerable: true,
  54257. configurable: true
  54258. });
  54259. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54260. /**
  54261. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54262. */
  54263. get: function () {
  54264. return this._computeBoundingBox;
  54265. },
  54266. /**
  54267. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54268. */
  54269. set: function (val) {
  54270. this._computeBoundingBox = val;
  54271. },
  54272. enumerable: true,
  54273. configurable: true
  54274. });
  54275. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54276. /**
  54277. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54278. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54279. * Default : `true`
  54280. */
  54281. get: function () {
  54282. return this._depthSortParticles;
  54283. },
  54284. /**
  54285. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54286. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54287. * Default : `true`
  54288. */
  54289. set: function (val) {
  54290. this._depthSortParticles = val;
  54291. },
  54292. enumerable: true,
  54293. configurable: true
  54294. });
  54295. // =======================================================================
  54296. // Particle behavior logic
  54297. // these following methods may be overwritten by the user to fit his needs
  54298. /**
  54299. * This function does nothing. It may be overwritten to set all the particle first values.
  54300. * The SPS doesn't call this function, you may have to call it by your own.
  54301. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54302. */
  54303. SolidParticleSystem.prototype.initParticles = function () {
  54304. };
  54305. /**
  54306. * This function does nothing. It may be overwritten to recycle a particle.
  54307. * The SPS doesn't call this function, you may have to call it by your own.
  54308. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54309. * @param particle The particle to recycle
  54310. * @returns the recycled particle
  54311. */
  54312. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54313. return particle;
  54314. };
  54315. /**
  54316. * Updates a particle : this function should be overwritten by the user.
  54317. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54318. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54319. * @example : just set a particle position or velocity and recycle conditions
  54320. * @param particle The particle to update
  54321. * @returns the updated particle
  54322. */
  54323. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54324. return particle;
  54325. };
  54326. /**
  54327. * Updates a vertex of a particle : it can be overwritten by the user.
  54328. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54329. * @param particle the current particle
  54330. * @param vertex the current index of the current particle
  54331. * @param pt the index of the current vertex in the particle shape
  54332. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54333. * @example : just set a vertex particle position
  54334. * @returns the updated vertex
  54335. */
  54336. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54337. return vertex;
  54338. };
  54339. /**
  54340. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54341. * This does nothing and may be overwritten by the user.
  54342. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54343. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54344. * @param update the boolean update value actually passed to setParticles()
  54345. */
  54346. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54347. };
  54348. /**
  54349. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54350. * This will be passed three parameters.
  54351. * This does nothing and may be overwritten by the user.
  54352. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54353. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54354. * @param update the boolean update value actually passed to setParticles()
  54355. */
  54356. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54357. };
  54358. return SolidParticleSystem;
  54359. }());
  54360. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54361. })(BABYLON || (BABYLON = {}));
  54362. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54363. var BABYLON;
  54364. (function (BABYLON) {
  54365. var ShaderMaterial = /** @class */ (function (_super) {
  54366. __extends(ShaderMaterial, _super);
  54367. function ShaderMaterial(name, scene, shaderPath, options) {
  54368. var _this = _super.call(this, name, scene) || this;
  54369. _this._textures = {};
  54370. _this._textureArrays = {};
  54371. _this._floats = {};
  54372. _this._ints = {};
  54373. _this._floatsArrays = {};
  54374. _this._colors3 = {};
  54375. _this._colors3Arrays = {};
  54376. _this._colors4 = {};
  54377. _this._vectors2 = {};
  54378. _this._vectors3 = {};
  54379. _this._vectors4 = {};
  54380. _this._matrices = {};
  54381. _this._matrices3x3 = {};
  54382. _this._matrices2x2 = {};
  54383. _this._vectors2Arrays = {};
  54384. _this._vectors3Arrays = {};
  54385. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54386. _this._shaderPath = shaderPath;
  54387. options.needAlphaBlending = options.needAlphaBlending || false;
  54388. options.needAlphaTesting = options.needAlphaTesting || false;
  54389. options.attributes = options.attributes || ["position", "normal", "uv"];
  54390. options.uniforms = options.uniforms || ["worldViewProjection"];
  54391. options.uniformBuffers = options.uniformBuffers || [];
  54392. options.samplers = options.samplers || [];
  54393. options.defines = options.defines || [];
  54394. _this._options = options;
  54395. return _this;
  54396. }
  54397. ShaderMaterial.prototype.getClassName = function () {
  54398. return "ShaderMaterial";
  54399. };
  54400. ShaderMaterial.prototype.needAlphaBlending = function () {
  54401. return this._options.needAlphaBlending;
  54402. };
  54403. ShaderMaterial.prototype.needAlphaTesting = function () {
  54404. return this._options.needAlphaTesting;
  54405. };
  54406. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54407. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54408. this._options.uniforms.push(uniformName);
  54409. }
  54410. };
  54411. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54412. if (this._options.samplers.indexOf(name) === -1) {
  54413. this._options.samplers.push(name);
  54414. }
  54415. this._textures[name] = texture;
  54416. return this;
  54417. };
  54418. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54419. if (this._options.samplers.indexOf(name) === -1) {
  54420. this._options.samplers.push(name);
  54421. }
  54422. this._checkUniform(name);
  54423. this._textureArrays[name] = textures;
  54424. return this;
  54425. };
  54426. ShaderMaterial.prototype.setFloat = function (name, value) {
  54427. this._checkUniform(name);
  54428. this._floats[name] = value;
  54429. return this;
  54430. };
  54431. ShaderMaterial.prototype.setInt = function (name, value) {
  54432. this._checkUniform(name);
  54433. this._ints[name] = value;
  54434. return this;
  54435. };
  54436. ShaderMaterial.prototype.setFloats = function (name, value) {
  54437. this._checkUniform(name);
  54438. this._floatsArrays[name] = value;
  54439. return this;
  54440. };
  54441. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54442. this._checkUniform(name);
  54443. this._colors3[name] = value;
  54444. return this;
  54445. };
  54446. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54447. this._checkUniform(name);
  54448. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54449. color.toArray(arr, arr.length);
  54450. return arr;
  54451. }, []);
  54452. return this;
  54453. };
  54454. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54455. this._checkUniform(name);
  54456. this._colors4[name] = value;
  54457. return this;
  54458. };
  54459. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54460. this._checkUniform(name);
  54461. this._vectors2[name] = value;
  54462. return this;
  54463. };
  54464. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54465. this._checkUniform(name);
  54466. this._vectors3[name] = value;
  54467. return this;
  54468. };
  54469. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54470. this._checkUniform(name);
  54471. this._vectors4[name] = value;
  54472. return this;
  54473. };
  54474. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54475. this._checkUniform(name);
  54476. this._matrices[name] = value;
  54477. return this;
  54478. };
  54479. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54480. this._checkUniform(name);
  54481. this._matrices3x3[name] = value;
  54482. return this;
  54483. };
  54484. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54485. this._checkUniform(name);
  54486. this._matrices2x2[name] = value;
  54487. return this;
  54488. };
  54489. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54490. this._checkUniform(name);
  54491. this._vectors2Arrays[name] = value;
  54492. return this;
  54493. };
  54494. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54495. this._checkUniform(name);
  54496. this._vectors3Arrays[name] = value;
  54497. return this;
  54498. };
  54499. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54500. if (!mesh) {
  54501. return true;
  54502. }
  54503. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54504. return false;
  54505. }
  54506. return false;
  54507. };
  54508. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54509. var scene = this.getScene();
  54510. var engine = scene.getEngine();
  54511. if (!this.checkReadyOnEveryCall) {
  54512. if (this._renderId === scene.getRenderId()) {
  54513. if (this._checkCache(scene, mesh, useInstances)) {
  54514. return true;
  54515. }
  54516. }
  54517. }
  54518. // Instances
  54519. var defines = [];
  54520. var attribs = [];
  54521. var fallbacks = new BABYLON.EffectFallbacks();
  54522. if (useInstances) {
  54523. defines.push("#define INSTANCES");
  54524. }
  54525. for (var index = 0; index < this._options.defines.length; index++) {
  54526. defines.push(this._options.defines[index]);
  54527. }
  54528. for (var index = 0; index < this._options.attributes.length; index++) {
  54529. attribs.push(this._options.attributes[index]);
  54530. }
  54531. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54532. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54533. defines.push("#define VERTEXCOLOR");
  54534. }
  54535. // Bones
  54536. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54537. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54538. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54539. if (mesh.numBoneInfluencers > 4) {
  54540. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54541. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54542. }
  54543. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54544. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54545. fallbacks.addCPUSkinningFallback(0, mesh);
  54546. if (this._options.uniforms.indexOf("mBones") === -1) {
  54547. this._options.uniforms.push("mBones");
  54548. }
  54549. }
  54550. else {
  54551. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54552. }
  54553. // Textures
  54554. for (var name in this._textures) {
  54555. if (!this._textures[name].isReady()) {
  54556. return false;
  54557. }
  54558. }
  54559. // Alpha test
  54560. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  54561. defines.push("#define ALPHATEST");
  54562. }
  54563. var previousEffect = this._effect;
  54564. var join = defines.join("\n");
  54565. this._effect = engine.createEffect(this._shaderPath, {
  54566. attributes: attribs,
  54567. uniformsNames: this._options.uniforms,
  54568. uniformBuffersNames: this._options.uniformBuffers,
  54569. samplers: this._options.samplers,
  54570. defines: join,
  54571. fallbacks: fallbacks,
  54572. onCompiled: this.onCompiled,
  54573. onError: this.onError
  54574. }, engine);
  54575. if (!this._effect.isReady()) {
  54576. return false;
  54577. }
  54578. if (previousEffect !== this._effect) {
  54579. scene.resetCachedMaterial();
  54580. }
  54581. this._renderId = scene.getRenderId();
  54582. return true;
  54583. };
  54584. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54585. var scene = this.getScene();
  54586. if (!this._effect) {
  54587. return;
  54588. }
  54589. if (this._options.uniforms.indexOf("world") !== -1) {
  54590. this._effect.setMatrix("world", world);
  54591. }
  54592. if (this._options.uniforms.indexOf("worldView") !== -1) {
  54593. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  54594. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  54595. }
  54596. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  54597. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  54598. }
  54599. };
  54600. ShaderMaterial.prototype.bind = function (world, mesh) {
  54601. // Std values
  54602. this.bindOnlyWorldMatrix(world);
  54603. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  54604. if (this._options.uniforms.indexOf("view") !== -1) {
  54605. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  54606. }
  54607. if (this._options.uniforms.indexOf("projection") !== -1) {
  54608. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  54609. }
  54610. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  54611. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  54612. }
  54613. // Bones
  54614. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54615. var name;
  54616. // Texture
  54617. for (name in this._textures) {
  54618. this._effect.setTexture(name, this._textures[name]);
  54619. }
  54620. // Texture arrays
  54621. for (name in this._textureArrays) {
  54622. this._effect.setTextureArray(name, this._textureArrays[name]);
  54623. }
  54624. // Int
  54625. for (name in this._ints) {
  54626. this._effect.setInt(name, this._ints[name]);
  54627. }
  54628. // Float
  54629. for (name in this._floats) {
  54630. this._effect.setFloat(name, this._floats[name]);
  54631. }
  54632. // Floats
  54633. for (name in this._floatsArrays) {
  54634. this._effect.setArray(name, this._floatsArrays[name]);
  54635. }
  54636. // Color3
  54637. for (name in this._colors3) {
  54638. this._effect.setColor3(name, this._colors3[name]);
  54639. }
  54640. for (name in this._colors3Arrays) {
  54641. this._effect.setArray3(name, this._colors3Arrays[name]);
  54642. }
  54643. // Color4
  54644. for (name in this._colors4) {
  54645. var color = this._colors4[name];
  54646. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54647. }
  54648. // Vector2
  54649. for (name in this._vectors2) {
  54650. this._effect.setVector2(name, this._vectors2[name]);
  54651. }
  54652. // Vector3
  54653. for (name in this._vectors3) {
  54654. this._effect.setVector3(name, this._vectors3[name]);
  54655. }
  54656. // Vector4
  54657. for (name in this._vectors4) {
  54658. this._effect.setVector4(name, this._vectors4[name]);
  54659. }
  54660. // Matrix
  54661. for (name in this._matrices) {
  54662. this._effect.setMatrix(name, this._matrices[name]);
  54663. }
  54664. // Matrix 3x3
  54665. for (name in this._matrices3x3) {
  54666. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  54667. }
  54668. // Matrix 2x2
  54669. for (name in this._matrices2x2) {
  54670. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  54671. }
  54672. // Vector2Array
  54673. for (name in this._vectors2Arrays) {
  54674. this._effect.setArray2(name, this._vectors2Arrays[name]);
  54675. }
  54676. // Vector3Array
  54677. for (name in this._vectors3Arrays) {
  54678. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54679. }
  54680. }
  54681. this._afterBind(mesh);
  54682. };
  54683. ShaderMaterial.prototype.getActiveTextures = function () {
  54684. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54685. for (var name in this._textures) {
  54686. activeTextures.push(this._textures[name]);
  54687. }
  54688. for (var name in this._textureArrays) {
  54689. var array = this._textureArrays[name];
  54690. for (var index = 0; index < array.length; index++) {
  54691. activeTextures.push(array[index]);
  54692. }
  54693. }
  54694. return activeTextures;
  54695. };
  54696. ShaderMaterial.prototype.hasTexture = function (texture) {
  54697. if (_super.prototype.hasTexture.call(this, texture)) {
  54698. return true;
  54699. }
  54700. for (var name in this._textures) {
  54701. if (this._textures[name] === texture) {
  54702. return true;
  54703. }
  54704. }
  54705. for (var name in this._textureArrays) {
  54706. var array = this._textureArrays[name];
  54707. for (var index = 0; index < array.length; index++) {
  54708. if (array[index] === texture) {
  54709. return true;
  54710. }
  54711. }
  54712. }
  54713. return false;
  54714. };
  54715. ShaderMaterial.prototype.clone = function (name) {
  54716. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54717. return newShaderMaterial;
  54718. };
  54719. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54720. if (forceDisposeTextures) {
  54721. var name;
  54722. for (name in this._textures) {
  54723. this._textures[name].dispose();
  54724. }
  54725. for (name in this._textureArrays) {
  54726. var array = this._textureArrays[name];
  54727. for (var index = 0; index < array.length; index++) {
  54728. array[index].dispose();
  54729. }
  54730. }
  54731. }
  54732. this._textures = {};
  54733. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54734. };
  54735. ShaderMaterial.prototype.serialize = function () {
  54736. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54737. serializationObject.customType = "BABYLON.ShaderMaterial";
  54738. serializationObject.options = this._options;
  54739. serializationObject.shaderPath = this._shaderPath;
  54740. var name;
  54741. // Texture
  54742. serializationObject.textures = {};
  54743. for (name in this._textures) {
  54744. serializationObject.textures[name] = this._textures[name].serialize();
  54745. }
  54746. // Texture arrays
  54747. serializationObject.textureArrays = {};
  54748. for (name in this._textureArrays) {
  54749. serializationObject.textureArrays[name] = [];
  54750. var array = this._textureArrays[name];
  54751. for (var index = 0; index < array.length; index++) {
  54752. serializationObject.textureArrays[name].push(array[index].serialize());
  54753. }
  54754. }
  54755. // Float
  54756. serializationObject.floats = {};
  54757. for (name in this._floats) {
  54758. serializationObject.floats[name] = this._floats[name];
  54759. }
  54760. // Float s
  54761. serializationObject.FloatArrays = {};
  54762. for (name in this._floatsArrays) {
  54763. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54764. }
  54765. // Color3
  54766. serializationObject.colors3 = {};
  54767. for (name in this._colors3) {
  54768. serializationObject.colors3[name] = this._colors3[name].asArray();
  54769. }
  54770. // Color3 array
  54771. serializationObject.colors3Arrays = {};
  54772. for (name in this._colors3Arrays) {
  54773. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54774. }
  54775. // Color4
  54776. serializationObject.colors4 = {};
  54777. for (name in this._colors4) {
  54778. serializationObject.colors4[name] = this._colors4[name].asArray();
  54779. }
  54780. // Vector2
  54781. serializationObject.vectors2 = {};
  54782. for (name in this._vectors2) {
  54783. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54784. }
  54785. // Vector3
  54786. serializationObject.vectors3 = {};
  54787. for (name in this._vectors3) {
  54788. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54789. }
  54790. // Vector4
  54791. serializationObject.vectors4 = {};
  54792. for (name in this._vectors4) {
  54793. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54794. }
  54795. // Matrix
  54796. serializationObject.matrices = {};
  54797. for (name in this._matrices) {
  54798. serializationObject.matrices[name] = this._matrices[name].asArray();
  54799. }
  54800. // Matrix 3x3
  54801. serializationObject.matrices3x3 = {};
  54802. for (name in this._matrices3x3) {
  54803. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54804. }
  54805. // Matrix 2x2
  54806. serializationObject.matrices2x2 = {};
  54807. for (name in this._matrices2x2) {
  54808. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54809. }
  54810. // Vector2Array
  54811. serializationObject.vectors2Arrays = {};
  54812. for (name in this._vectors2Arrays) {
  54813. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54814. }
  54815. // Vector3Array
  54816. serializationObject.vectors3Arrays = {};
  54817. for (name in this._vectors3Arrays) {
  54818. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54819. }
  54820. return serializationObject;
  54821. };
  54822. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54823. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54824. var name;
  54825. // Texture
  54826. for (name in source.textures) {
  54827. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54828. }
  54829. // Texture arrays
  54830. for (name in source.textureArrays) {
  54831. var array = source.textureArrays[name];
  54832. var textureArray = new Array();
  54833. for (var index = 0; index < array.length; index++) {
  54834. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54835. }
  54836. material.setTextureArray(name, textureArray);
  54837. }
  54838. // Float
  54839. for (name in source.floats) {
  54840. material.setFloat(name, source.floats[name]);
  54841. }
  54842. // Float s
  54843. for (name in source.floatsArrays) {
  54844. material.setFloats(name, source.floatsArrays[name]);
  54845. }
  54846. // Color3
  54847. for (name in source.colors3) {
  54848. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54849. }
  54850. // Color3 arrays
  54851. for (name in source.colors3Arrays) {
  54852. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54853. if (i % 3 === 0) {
  54854. arr.push([num]);
  54855. }
  54856. else {
  54857. arr[arr.length - 1].push(num);
  54858. }
  54859. return arr;
  54860. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54861. material.setColor3Array(name, colors);
  54862. }
  54863. // Color4
  54864. for (name in source.colors4) {
  54865. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54866. }
  54867. // Vector2
  54868. for (name in source.vectors2) {
  54869. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54870. }
  54871. // Vector3
  54872. for (name in source.vectors3) {
  54873. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54874. }
  54875. // Vector4
  54876. for (name in source.vectors4) {
  54877. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54878. }
  54879. // Matrix
  54880. for (name in source.matrices) {
  54881. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54882. }
  54883. // Matrix 3x3
  54884. for (name in source.matrices3x3) {
  54885. material.setMatrix3x3(name, source.matrices3x3[name]);
  54886. }
  54887. // Matrix 2x2
  54888. for (name in source.matrices2x2) {
  54889. material.setMatrix2x2(name, source.matrices2x2[name]);
  54890. }
  54891. // Vector2Array
  54892. for (name in source.vectors2Arrays) {
  54893. material.setArray2(name, source.vectors2Arrays[name]);
  54894. }
  54895. // Vector3Array
  54896. for (name in source.vectors3Arrays) {
  54897. material.setArray3(name, source.vectors3Arrays[name]);
  54898. }
  54899. return material;
  54900. };
  54901. return ShaderMaterial;
  54902. }(BABYLON.Material));
  54903. BABYLON.ShaderMaterial = ShaderMaterial;
  54904. })(BABYLON || (BABYLON = {}));
  54905. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54906. var BABYLON;
  54907. (function (BABYLON) {
  54908. var GroundMesh = /** @class */ (function (_super) {
  54909. __extends(GroundMesh, _super);
  54910. function GroundMesh(name, scene) {
  54911. var _this = _super.call(this, name, scene) || this;
  54912. _this.generateOctree = false;
  54913. return _this;
  54914. }
  54915. GroundMesh.prototype.getClassName = function () {
  54916. return "GroundMesh";
  54917. };
  54918. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54919. get: function () {
  54920. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54921. },
  54922. enumerable: true,
  54923. configurable: true
  54924. });
  54925. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54926. get: function () {
  54927. return this._subdivisionsX;
  54928. },
  54929. enumerable: true,
  54930. configurable: true
  54931. });
  54932. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54933. get: function () {
  54934. return this._subdivisionsY;
  54935. },
  54936. enumerable: true,
  54937. configurable: true
  54938. });
  54939. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54940. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54941. this._subdivisionsX = chunksCount;
  54942. this._subdivisionsY = chunksCount;
  54943. this.subdivide(chunksCount);
  54944. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54945. };
  54946. /**
  54947. * Returns a height (y) value in the Worl system :
  54948. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54949. * Returns the ground y position if (x, z) are outside the ground surface.
  54950. */
  54951. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54952. var world = this.getWorldMatrix();
  54953. var invMat = BABYLON.Tmp.Matrix[5];
  54954. world.invertToRef(invMat);
  54955. var tmpVect = BABYLON.Tmp.Vector3[8];
  54956. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54957. x = tmpVect.x;
  54958. z = tmpVect.z;
  54959. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54960. return this.position.y;
  54961. }
  54962. if (!this._heightQuads || this._heightQuads.length == 0) {
  54963. this._initHeightQuads();
  54964. this._computeHeightQuads();
  54965. }
  54966. var facet = this._getFacetAt(x, z);
  54967. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54968. // return y in the World system
  54969. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54970. return tmpVect.y;
  54971. };
  54972. /**
  54973. * Returns a normalized vector (Vector3) orthogonal to the ground
  54974. * at the ground coordinates (x, z) expressed in the World system.
  54975. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54976. */
  54977. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54978. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54979. this.getNormalAtCoordinatesToRef(x, z, normal);
  54980. return normal;
  54981. };
  54982. /**
  54983. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54984. * at the ground coordinates (x, z) expressed in the World system.
  54985. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54986. * Returns the GroundMesh.
  54987. */
  54988. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54989. var world = this.getWorldMatrix();
  54990. var tmpMat = BABYLON.Tmp.Matrix[5];
  54991. world.invertToRef(tmpMat);
  54992. var tmpVect = BABYLON.Tmp.Vector3[8];
  54993. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54994. x = tmpVect.x;
  54995. z = tmpVect.z;
  54996. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54997. return this;
  54998. }
  54999. if (!this._heightQuads || this._heightQuads.length == 0) {
  55000. this._initHeightQuads();
  55001. this._computeHeightQuads();
  55002. }
  55003. var facet = this._getFacetAt(x, z);
  55004. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55005. return this;
  55006. };
  55007. /**
  55008. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55009. * if the ground has been updated.
  55010. * This can be used in the render loop.
  55011. * Returns the GroundMesh.
  55012. */
  55013. GroundMesh.prototype.updateCoordinateHeights = function () {
  55014. if (!this._heightQuads || this._heightQuads.length == 0) {
  55015. this._initHeightQuads();
  55016. }
  55017. this._computeHeightQuads();
  55018. return this;
  55019. };
  55020. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55021. GroundMesh.prototype._getFacetAt = function (x, z) {
  55022. // retrieve col and row from x, z coordinates in the ground local system
  55023. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55024. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55025. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55026. var facet;
  55027. if (z < quad.slope.x * x + quad.slope.y) {
  55028. facet = quad.facet1;
  55029. }
  55030. else {
  55031. facet = quad.facet2;
  55032. }
  55033. return facet;
  55034. };
  55035. // Creates and populates the heightMap array with "facet" elements :
  55036. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55037. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55038. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55039. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55040. // Returns the GroundMesh.
  55041. GroundMesh.prototype._initHeightQuads = function () {
  55042. var subdivisionsX = this._subdivisionsX;
  55043. var subdivisionsY = this._subdivisionsY;
  55044. this._heightQuads = new Array();
  55045. for (var row = 0; row < subdivisionsY; row++) {
  55046. for (var col = 0; col < subdivisionsX; col++) {
  55047. 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) };
  55048. this._heightQuads[row * subdivisionsX + col] = quad;
  55049. }
  55050. }
  55051. return this;
  55052. };
  55053. // Compute each quad element values and update the the heightMap array :
  55054. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55055. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55056. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55057. // Returns the GroundMesh.
  55058. GroundMesh.prototype._computeHeightQuads = function () {
  55059. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55060. if (!positions) {
  55061. return this;
  55062. }
  55063. var v1 = BABYLON.Tmp.Vector3[3];
  55064. var v2 = BABYLON.Tmp.Vector3[2];
  55065. var v3 = BABYLON.Tmp.Vector3[1];
  55066. var v4 = BABYLON.Tmp.Vector3[0];
  55067. var v1v2 = BABYLON.Tmp.Vector3[4];
  55068. var v1v3 = BABYLON.Tmp.Vector3[5];
  55069. var v1v4 = BABYLON.Tmp.Vector3[6];
  55070. var norm1 = BABYLON.Tmp.Vector3[7];
  55071. var norm2 = BABYLON.Tmp.Vector3[8];
  55072. var i = 0;
  55073. var j = 0;
  55074. var k = 0;
  55075. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55076. var h = 0;
  55077. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55078. var d2 = 0;
  55079. var subdivisionsX = this._subdivisionsX;
  55080. var subdivisionsY = this._subdivisionsY;
  55081. for (var row = 0; row < subdivisionsY; row++) {
  55082. for (var col = 0; col < subdivisionsX; col++) {
  55083. i = col * 3;
  55084. j = row * (subdivisionsX + 1) * 3;
  55085. k = (row + 1) * (subdivisionsX + 1) * 3;
  55086. v1.x = positions[j + i];
  55087. v1.y = positions[j + i + 1];
  55088. v1.z = positions[j + i + 2];
  55089. v2.x = positions[j + i + 3];
  55090. v2.y = positions[j + i + 4];
  55091. v2.z = positions[j + i + 5];
  55092. v3.x = positions[k + i];
  55093. v3.y = positions[k + i + 1];
  55094. v3.z = positions[k + i + 2];
  55095. v4.x = positions[k + i + 3];
  55096. v4.y = positions[k + i + 4];
  55097. v4.z = positions[k + i + 5];
  55098. // 2D slope V1V4
  55099. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55100. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55101. // facet equations :
  55102. // we compute each facet normal vector
  55103. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55104. // we compute the value d by applying the equation to v1 which belongs to the plane
  55105. // then we store the facet equation in a Vector4
  55106. v2.subtractToRef(v1, v1v2);
  55107. v3.subtractToRef(v1, v1v3);
  55108. v4.subtractToRef(v1, v1v4);
  55109. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55110. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55111. norm1.normalize();
  55112. norm2.normalize();
  55113. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55114. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55115. var quad = this._heightQuads[row * subdivisionsX + col];
  55116. quad.slope.copyFromFloats(cd, h);
  55117. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55118. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55119. }
  55120. }
  55121. return this;
  55122. };
  55123. GroundMesh.prototype.serialize = function (serializationObject) {
  55124. _super.prototype.serialize.call(this, serializationObject);
  55125. serializationObject.subdivisionsX = this._subdivisionsX;
  55126. serializationObject.subdivisionsY = this._subdivisionsY;
  55127. serializationObject.minX = this._minX;
  55128. serializationObject.maxX = this._maxX;
  55129. serializationObject.minZ = this._minZ;
  55130. serializationObject.maxZ = this._maxZ;
  55131. serializationObject.width = this._width;
  55132. serializationObject.height = this._height;
  55133. };
  55134. GroundMesh.Parse = function (parsedMesh, scene) {
  55135. var result = new GroundMesh(parsedMesh.name, scene);
  55136. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55137. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55138. result._minX = parsedMesh.minX;
  55139. result._maxX = parsedMesh.maxX;
  55140. result._minZ = parsedMesh.minZ;
  55141. result._maxZ = parsedMesh.maxZ;
  55142. result._width = parsedMesh.width;
  55143. result._height = parsedMesh.height;
  55144. return result;
  55145. };
  55146. return GroundMesh;
  55147. }(BABYLON.Mesh));
  55148. BABYLON.GroundMesh = GroundMesh;
  55149. })(BABYLON || (BABYLON = {}));
  55150. //# sourceMappingURL=babylon.groundMesh.js.map
  55151. var BABYLON;
  55152. (function (BABYLON) {
  55153. /**
  55154. * Creates an instance based on a source mesh.
  55155. */
  55156. var InstancedMesh = /** @class */ (function (_super) {
  55157. __extends(InstancedMesh, _super);
  55158. function InstancedMesh(name, source) {
  55159. var _this = _super.call(this, name, source.getScene()) || this;
  55160. source.instances.push(_this);
  55161. _this._sourceMesh = source;
  55162. _this.position.copyFrom(source.position);
  55163. _this.rotation.copyFrom(source.rotation);
  55164. _this.scaling.copyFrom(source.scaling);
  55165. if (source.rotationQuaternion) {
  55166. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55167. }
  55168. _this.infiniteDistance = source.infiniteDistance;
  55169. _this.setPivotMatrix(source.getPivotMatrix());
  55170. _this.refreshBoundingInfo();
  55171. _this._syncSubMeshes();
  55172. return _this;
  55173. }
  55174. /**
  55175. * Returns the string "InstancedMesh".
  55176. */
  55177. InstancedMesh.prototype.getClassName = function () {
  55178. return "InstancedMesh";
  55179. };
  55180. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55181. // Methods
  55182. get: function () {
  55183. return this._sourceMesh.receiveShadows;
  55184. },
  55185. enumerable: true,
  55186. configurable: true
  55187. });
  55188. Object.defineProperty(InstancedMesh.prototype, "material", {
  55189. get: function () {
  55190. return this._sourceMesh.material;
  55191. },
  55192. enumerable: true,
  55193. configurable: true
  55194. });
  55195. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55196. get: function () {
  55197. return this._sourceMesh.visibility;
  55198. },
  55199. enumerable: true,
  55200. configurable: true
  55201. });
  55202. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55203. get: function () {
  55204. return this._sourceMesh.skeleton;
  55205. },
  55206. enumerable: true,
  55207. configurable: true
  55208. });
  55209. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55210. get: function () {
  55211. return this._sourceMesh.renderingGroupId;
  55212. },
  55213. set: function (value) {
  55214. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  55215. return;
  55216. }
  55217. //no-op with warning
  55218. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  55219. },
  55220. enumerable: true,
  55221. configurable: true
  55222. });
  55223. /**
  55224. * Returns the total number of vertices (integer).
  55225. */
  55226. InstancedMesh.prototype.getTotalVertices = function () {
  55227. return this._sourceMesh.getTotalVertices();
  55228. };
  55229. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55230. get: function () {
  55231. return this._sourceMesh;
  55232. },
  55233. enumerable: true,
  55234. configurable: true
  55235. });
  55236. /**
  55237. * Is this node ready to be used/rendered
  55238. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55239. * @return {boolean} is it ready
  55240. */
  55241. InstancedMesh.prototype.isReady = function (completeCheck) {
  55242. if (completeCheck === void 0) { completeCheck = false; }
  55243. return this._sourceMesh.isReady(completeCheck, true);
  55244. };
  55245. /**
  55246. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55247. */
  55248. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55249. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55250. };
  55251. /**
  55252. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55253. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55254. * The `data` are either a numeric array either a Float32Array.
  55255. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55256. * 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).
  55257. * Note that a new underlying VertexBuffer object is created each call.
  55258. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55259. *
  55260. * Possible `kind` values :
  55261. * - BABYLON.VertexBuffer.PositionKind
  55262. * - BABYLON.VertexBuffer.UVKind
  55263. * - BABYLON.VertexBuffer.UV2Kind
  55264. * - BABYLON.VertexBuffer.UV3Kind
  55265. * - BABYLON.VertexBuffer.UV4Kind
  55266. * - BABYLON.VertexBuffer.UV5Kind
  55267. * - BABYLON.VertexBuffer.UV6Kind
  55268. * - BABYLON.VertexBuffer.ColorKind
  55269. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55270. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55271. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55272. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55273. *
  55274. * Returns the Mesh.
  55275. */
  55276. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55277. if (this.sourceMesh) {
  55278. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55279. }
  55280. return this.sourceMesh;
  55281. };
  55282. /**
  55283. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55284. * If the mesh has no geometry, it is simply returned as it is.
  55285. * The `data` are either a numeric array either a Float32Array.
  55286. * No new underlying VertexBuffer object is created.
  55287. * 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.
  55288. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55289. *
  55290. * Possible `kind` values :
  55291. * - BABYLON.VertexBuffer.PositionKind
  55292. * - BABYLON.VertexBuffer.UVKind
  55293. * - BABYLON.VertexBuffer.UV2Kind
  55294. * - BABYLON.VertexBuffer.UV3Kind
  55295. * - BABYLON.VertexBuffer.UV4Kind
  55296. * - BABYLON.VertexBuffer.UV5Kind
  55297. * - BABYLON.VertexBuffer.UV6Kind
  55298. * - BABYLON.VertexBuffer.ColorKind
  55299. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55300. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55301. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55302. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55303. *
  55304. * Returns the Mesh.
  55305. */
  55306. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55307. if (this.sourceMesh) {
  55308. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55309. }
  55310. return this.sourceMesh;
  55311. };
  55312. /**
  55313. * Sets the mesh indices.
  55314. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  55315. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  55316. * This method creates a new index buffer each call.
  55317. * Returns the Mesh.
  55318. */
  55319. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  55320. if (totalVertices === void 0) { totalVertices = null; }
  55321. if (this.sourceMesh) {
  55322. this.sourceMesh.setIndices(indices, totalVertices);
  55323. }
  55324. return this.sourceMesh;
  55325. };
  55326. /**
  55327. * Boolean : True if the mesh owns the requested kind of data.
  55328. */
  55329. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55330. return this._sourceMesh.isVerticesDataPresent(kind);
  55331. };
  55332. /**
  55333. * Returns an array of indices (IndicesArray).
  55334. */
  55335. InstancedMesh.prototype.getIndices = function () {
  55336. return this._sourceMesh.getIndices();
  55337. };
  55338. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55339. get: function () {
  55340. return this._sourceMesh._positions;
  55341. },
  55342. enumerable: true,
  55343. configurable: true
  55344. });
  55345. /**
  55346. * Sets a new updated BoundingInfo to the mesh.
  55347. * Returns the mesh.
  55348. */
  55349. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55350. var meshBB = this._sourceMesh.getBoundingInfo();
  55351. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55352. this._updateBoundingInfo();
  55353. return this;
  55354. };
  55355. InstancedMesh.prototype._preActivate = function () {
  55356. if (this._currentLOD) {
  55357. this._currentLOD._preActivate();
  55358. }
  55359. return this;
  55360. };
  55361. InstancedMesh.prototype._activate = function (renderId) {
  55362. if (this._currentLOD) {
  55363. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55364. }
  55365. return this;
  55366. };
  55367. /**
  55368. * Returns the current associated LOD AbstractMesh.
  55369. */
  55370. InstancedMesh.prototype.getLOD = function (camera) {
  55371. if (!camera) {
  55372. return this;
  55373. }
  55374. var boundingInfo = this.getBoundingInfo();
  55375. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55376. if (this._currentLOD === this.sourceMesh) {
  55377. return this;
  55378. }
  55379. return this._currentLOD;
  55380. };
  55381. InstancedMesh.prototype._syncSubMeshes = function () {
  55382. this.releaseSubMeshes();
  55383. if (this._sourceMesh.subMeshes) {
  55384. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55385. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55386. }
  55387. }
  55388. return this;
  55389. };
  55390. InstancedMesh.prototype._generatePointsArray = function () {
  55391. return this._sourceMesh._generatePointsArray();
  55392. };
  55393. /**
  55394. * Creates a new InstancedMesh from the current mesh.
  55395. * - name (string) : the cloned mesh name
  55396. * - newParent (optional Node) : the optional Node to parent the clone to.
  55397. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55398. *
  55399. * Returns the clone.
  55400. */
  55401. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55402. var result = this._sourceMesh.createInstance(name);
  55403. // Deep copy
  55404. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55405. // Bounding info
  55406. this.refreshBoundingInfo();
  55407. // Parent
  55408. if (newParent) {
  55409. result.parent = newParent;
  55410. }
  55411. if (!doNotCloneChildren) {
  55412. // Children
  55413. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55414. var mesh = this.getScene().meshes[index];
  55415. if (mesh.parent === this) {
  55416. mesh.clone(mesh.name, result);
  55417. }
  55418. }
  55419. }
  55420. result.computeWorldMatrix(true);
  55421. return result;
  55422. };
  55423. /**
  55424. * Disposes the InstancedMesh.
  55425. * Returns nothing.
  55426. */
  55427. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  55428. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  55429. // Remove from mesh
  55430. var index = this._sourceMesh.instances.indexOf(this);
  55431. this._sourceMesh.instances.splice(index, 1);
  55432. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  55433. };
  55434. return InstancedMesh;
  55435. }(BABYLON.AbstractMesh));
  55436. BABYLON.InstancedMesh = InstancedMesh;
  55437. })(BABYLON || (BABYLON = {}));
  55438. //# sourceMappingURL=babylon.instancedMesh.js.map
  55439. var BABYLON;
  55440. (function (BABYLON) {
  55441. var LinesMesh = /** @class */ (function (_super) {
  55442. __extends(LinesMesh, _super);
  55443. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55444. if (scene === void 0) { scene = null; }
  55445. if (parent === void 0) { parent = null; }
  55446. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55447. _this.useVertexColor = useVertexColor;
  55448. _this.useVertexAlpha = useVertexAlpha;
  55449. _this.color = new BABYLON.Color3(1, 1, 1);
  55450. _this.alpha = 1;
  55451. if (source) {
  55452. _this.color = source.color.clone();
  55453. _this.alpha = source.alpha;
  55454. _this.useVertexColor = source.useVertexColor;
  55455. _this.useVertexAlpha = source.useVertexAlpha;
  55456. }
  55457. _this._intersectionThreshold = 0.1;
  55458. var defines = [];
  55459. var options = {
  55460. attributes: [BABYLON.VertexBuffer.PositionKind],
  55461. uniforms: ["world", "viewProjection"],
  55462. needAlphaBlending: true,
  55463. defines: defines
  55464. };
  55465. if (useVertexAlpha === false) {
  55466. options.needAlphaBlending = false;
  55467. }
  55468. if (!useVertexColor) {
  55469. options.uniforms.push("color");
  55470. }
  55471. else {
  55472. options.defines.push("#define VERTEXCOLOR");
  55473. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55474. }
  55475. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55476. return _this;
  55477. }
  55478. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55479. /**
  55480. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55481. * This margin is expressed in world space coordinates, so its value may vary.
  55482. * Default value is 0.1
  55483. * @returns the intersection Threshold value.
  55484. */
  55485. get: function () {
  55486. return this._intersectionThreshold;
  55487. },
  55488. /**
  55489. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55490. * This margin is expressed in world space coordinates, so its value may vary.
  55491. * @param value the new threshold to apply
  55492. */
  55493. set: function (value) {
  55494. if (this._intersectionThreshold === value) {
  55495. return;
  55496. }
  55497. this._intersectionThreshold = value;
  55498. if (this.geometry) {
  55499. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55500. }
  55501. },
  55502. enumerable: true,
  55503. configurable: true
  55504. });
  55505. /**
  55506. * Returns the string "LineMesh"
  55507. */
  55508. LinesMesh.prototype.getClassName = function () {
  55509. return "LinesMesh";
  55510. };
  55511. Object.defineProperty(LinesMesh.prototype, "material", {
  55512. get: function () {
  55513. return this._colorShader;
  55514. },
  55515. set: function (value) {
  55516. // Do nothing
  55517. },
  55518. enumerable: true,
  55519. configurable: true
  55520. });
  55521. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55522. get: function () {
  55523. return false;
  55524. },
  55525. enumerable: true,
  55526. configurable: true
  55527. });
  55528. LinesMesh.prototype.createInstance = function (name) {
  55529. throw new Error("LinesMeshes do not support createInstance.");
  55530. };
  55531. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55532. if (!this._geometry) {
  55533. return this;
  55534. }
  55535. // VBOs
  55536. this._geometry._bind(this._colorShader.getEffect());
  55537. // Color
  55538. if (!this.useVertexColor) {
  55539. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55540. }
  55541. return this;
  55542. };
  55543. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55544. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55545. return this;
  55546. }
  55547. var engine = this.getScene().getEngine();
  55548. // Draw order
  55549. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  55550. return this;
  55551. };
  55552. LinesMesh.prototype.dispose = function (doNotRecurse) {
  55553. this._colorShader.dispose();
  55554. _super.prototype.dispose.call(this, doNotRecurse);
  55555. };
  55556. /**
  55557. * Returns a new LineMesh object cloned from the current one.
  55558. */
  55559. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55560. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  55561. };
  55562. return LinesMesh;
  55563. }(BABYLON.Mesh));
  55564. BABYLON.LinesMesh = LinesMesh;
  55565. })(BABYLON || (BABYLON = {}));
  55566. //# sourceMappingURL=babylon.linesMesh.js.map
  55567. var BABYLON;
  55568. (function (BABYLON) {
  55569. var MeshBuilder = /** @class */ (function () {
  55570. function MeshBuilder() {
  55571. }
  55572. MeshBuilder.updateSideOrientation = function (orientation) {
  55573. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  55574. return BABYLON.Mesh.DOUBLESIDE;
  55575. }
  55576. if (orientation === undefined || orientation === null) {
  55577. return BABYLON.Mesh.FRONTSIDE;
  55578. }
  55579. return orientation;
  55580. };
  55581. /**
  55582. * Creates a box mesh.
  55583. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  55584. * The parameter `size` sets the size (float) of each box side (default 1).
  55585. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  55586. * 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).
  55587. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55588. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55589. * 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).
  55590. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55591. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55592. */
  55593. MeshBuilder.CreateBox = function (name, options, scene) {
  55594. if (scene === void 0) { scene = null; }
  55595. var box = new BABYLON.Mesh(name, scene);
  55596. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55597. box._originalBuilderSideOrientation = options.sideOrientation;
  55598. var vertexData = BABYLON.VertexData.CreateBox(options);
  55599. vertexData.applyToMesh(box, options.updatable);
  55600. return box;
  55601. };
  55602. /**
  55603. * Creates a sphere mesh.
  55604. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  55605. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  55606. * 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`).
  55607. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  55608. * 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
  55609. * 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).
  55610. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55611. * 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).
  55612. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55613. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55614. */
  55615. MeshBuilder.CreateSphere = function (name, options, scene) {
  55616. var sphere = new BABYLON.Mesh(name, scene);
  55617. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55618. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55619. var vertexData = BABYLON.VertexData.CreateSphere(options);
  55620. vertexData.applyToMesh(sphere, options.updatable);
  55621. return sphere;
  55622. };
  55623. /**
  55624. * Creates a plane polygonal mesh. By default, this is a disc.
  55625. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  55626. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  55627. * 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.
  55628. * 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
  55629. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55630. * 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).
  55631. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55632. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55633. */
  55634. MeshBuilder.CreateDisc = function (name, options, scene) {
  55635. if (scene === void 0) { scene = null; }
  55636. var disc = new BABYLON.Mesh(name, scene);
  55637. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55638. disc._originalBuilderSideOrientation = options.sideOrientation;
  55639. var vertexData = BABYLON.VertexData.CreateDisc(options);
  55640. vertexData.applyToMesh(disc, options.updatable);
  55641. return disc;
  55642. };
  55643. /**
  55644. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  55645. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  55646. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  55647. * 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`).
  55648. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  55649. * 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.
  55650. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55651. * 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).
  55652. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55653. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55654. */
  55655. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  55656. var sphere = new BABYLON.Mesh(name, scene);
  55657. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55658. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55659. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  55660. vertexData.applyToMesh(sphere, options.updatable);
  55661. return sphere;
  55662. };
  55663. ;
  55664. /**
  55665. * Creates a ribbon mesh.
  55666. * 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.
  55667. *
  55668. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  55669. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  55670. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  55671. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  55672. * 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.
  55673. * 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.
  55674. * 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
  55675. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55676. * 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).
  55677. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55678. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55679. * 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.
  55680. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55681. * 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
  55682. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55683. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55684. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55685. */
  55686. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55687. if (scene === void 0) { scene = null; }
  55688. var pathArray = options.pathArray;
  55689. var closeArray = options.closeArray;
  55690. var closePath = options.closePath;
  55691. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55692. var instance = options.instance;
  55693. var updatable = options.updatable;
  55694. if (instance) {
  55695. // positionFunction : ribbon case
  55696. // only pathArray and sideOrientation parameters are taken into account for positions update
  55697. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55698. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55699. var positionFunction = function (positions) {
  55700. var minlg = pathArray[0].length;
  55701. var i = 0;
  55702. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55703. for (var si = 1; si <= ns; si++) {
  55704. for (var p = 0; p < pathArray.length; p++) {
  55705. var path = pathArray[p];
  55706. var l = path.length;
  55707. minlg = (minlg < l) ? minlg : l;
  55708. var j = 0;
  55709. while (j < minlg) {
  55710. positions[i] = path[j].x;
  55711. positions[i + 1] = path[j].y;
  55712. positions[i + 2] = path[j].z;
  55713. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55714. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55715. }
  55716. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55717. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55718. }
  55719. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55720. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55721. }
  55722. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55723. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55724. }
  55725. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55726. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55727. }
  55728. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55729. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55730. }
  55731. j++;
  55732. i += 3;
  55733. }
  55734. if (instance._closePath) {
  55735. positions[i] = path[0].x;
  55736. positions[i + 1] = path[0].y;
  55737. positions[i + 2] = path[0].z;
  55738. i += 3;
  55739. }
  55740. }
  55741. }
  55742. };
  55743. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55744. positionFunction(positions);
  55745. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55746. instance._boundingInfo.update(instance._worldMatrix);
  55747. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55748. if (options.colors) {
  55749. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55750. for (var c = 0; c < options.colors.length; c++) {
  55751. colors[c * 4] = options.colors[c].r;
  55752. colors[c * 4 + 1] = options.colors[c].g;
  55753. colors[c * 4 + 2] = options.colors[c].b;
  55754. colors[c * 4 + 3] = options.colors[c].a;
  55755. }
  55756. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55757. }
  55758. if (options.uvs) {
  55759. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55760. for (var i = 0; i < options.uvs.length; i++) {
  55761. uvs[i * 2] = options.uvs[i].x;
  55762. uvs[i * 2 + 1] = options.uvs[i].y;
  55763. }
  55764. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55765. }
  55766. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55767. var indices = instance.getIndices();
  55768. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55769. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55770. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55771. if (instance._closePath) {
  55772. var indexFirst = 0;
  55773. var indexLast = 0;
  55774. for (var p = 0; p < pathArray.length; p++) {
  55775. indexFirst = instance._idx[p] * 3;
  55776. if (p + 1 < pathArray.length) {
  55777. indexLast = (instance._idx[p + 1] - 1) * 3;
  55778. }
  55779. else {
  55780. indexLast = normals.length - 3;
  55781. }
  55782. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55783. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55784. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55785. normals[indexLast] = normals[indexFirst];
  55786. normals[indexLast + 1] = normals[indexFirst + 1];
  55787. normals[indexLast + 2] = normals[indexFirst + 2];
  55788. }
  55789. }
  55790. if (!(instance.areNormalsFrozen)) {
  55791. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55792. }
  55793. }
  55794. return instance;
  55795. }
  55796. else {
  55797. var ribbon = new BABYLON.Mesh(name, scene);
  55798. ribbon._originalBuilderSideOrientation = sideOrientation;
  55799. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55800. if (closePath) {
  55801. ribbon._idx = vertexData._idx;
  55802. }
  55803. ribbon._closePath = closePath;
  55804. ribbon._closeArray = closeArray;
  55805. vertexData.applyToMesh(ribbon, updatable);
  55806. return ribbon;
  55807. }
  55808. };
  55809. /**
  55810. * Creates a cylinder or a cone mesh.
  55811. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55812. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55813. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55814. * 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.
  55815. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55816. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55817. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55818. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55819. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55820. * 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).
  55821. * 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
  55822. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55823. * 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
  55824. * 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.
  55825. * If `enclose` is false, a ring surface is one element.
  55826. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55827. * 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
  55828. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55829. * 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).
  55830. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55831. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55832. */
  55833. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55834. var cylinder = new BABYLON.Mesh(name, scene);
  55835. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55836. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55837. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55838. vertexData.applyToMesh(cylinder, options.updatable);
  55839. return cylinder;
  55840. };
  55841. /**
  55842. * Creates a torus mesh.
  55843. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55844. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55845. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55846. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55847. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55848. * 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).
  55849. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55851. */
  55852. MeshBuilder.CreateTorus = function (name, options, scene) {
  55853. var torus = new BABYLON.Mesh(name, scene);
  55854. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55855. torus._originalBuilderSideOrientation = options.sideOrientation;
  55856. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55857. vertexData.applyToMesh(torus, options.updatable);
  55858. return torus;
  55859. };
  55860. /**
  55861. * Creates a torus knot mesh.
  55862. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55863. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55864. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55865. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55866. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55867. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55868. * 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).
  55869. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55870. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55871. */
  55872. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55873. var torusKnot = new BABYLON.Mesh(name, scene);
  55874. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55875. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55876. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55877. vertexData.applyToMesh(torusKnot, options.updatable);
  55878. return torusKnot;
  55879. };
  55880. /**
  55881. * Creates a line system mesh.
  55882. * A line system is a pool of many lines gathered in a single mesh.
  55883. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55884. * 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.
  55885. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55886. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55887. * 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
  55888. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55889. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55890. * 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
  55891. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55892. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55893. */
  55894. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55895. var instance = options.instance;
  55896. var lines = options.lines;
  55897. var colors = options.colors;
  55898. if (instance) {
  55899. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55900. var vertexColor;
  55901. var lineColors;
  55902. if (colors) {
  55903. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55904. }
  55905. var i = 0;
  55906. var c = 0;
  55907. for (var l = 0; l < lines.length; l++) {
  55908. var points = lines[l];
  55909. for (var p = 0; p < points.length; p++) {
  55910. positions[i] = points[p].x;
  55911. positions[i + 1] = points[p].y;
  55912. positions[i + 2] = points[p].z;
  55913. if (colors && vertexColor) {
  55914. lineColors = colors[l];
  55915. vertexColor[c] = lineColors[p].r;
  55916. vertexColor[c + 1] = lineColors[p].g;
  55917. vertexColor[c + 2] = lineColors[p].b;
  55918. vertexColor[c + 3] = lineColors[p].a;
  55919. c += 4;
  55920. }
  55921. i += 3;
  55922. }
  55923. }
  55924. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55925. if (colors && vertexColor) {
  55926. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55927. }
  55928. return instance;
  55929. }
  55930. // line system creation
  55931. var useVertexColor = (colors) ? true : false;
  55932. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55933. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55934. vertexData.applyToMesh(lineSystem, options.updatable);
  55935. return lineSystem;
  55936. };
  55937. /**
  55938. * Creates a line mesh.
  55939. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55940. * 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.
  55941. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55942. * The parameter `points` is an array successive Vector3.
  55943. * 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
  55944. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55945. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55946. * When updating an instance, remember that only point positions can change, not the number of points.
  55947. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55948. */
  55949. MeshBuilder.CreateLines = function (name, options, scene) {
  55950. if (scene === void 0) { scene = null; }
  55951. var colors = (options.colors) ? [options.colors] : null;
  55952. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55953. return lines;
  55954. };
  55955. /**
  55956. * Creates a dashed line mesh.
  55957. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55958. * 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.
  55959. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55960. * The parameter `points` is an array successive Vector3.
  55961. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55962. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55963. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55964. * 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
  55965. * When updating an instance, remember that only point positions can change, not the number of points.
  55966. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55967. */
  55968. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55969. if (scene === void 0) { scene = null; }
  55970. var points = options.points;
  55971. var instance = options.instance;
  55972. var gapSize = options.gapSize || 1;
  55973. var dashSize = options.dashSize || 3;
  55974. if (instance) {
  55975. var positionFunction = function (positions) {
  55976. var curvect = BABYLON.Vector3.Zero();
  55977. var nbSeg = positions.length / 6;
  55978. var lg = 0;
  55979. var nb = 0;
  55980. var shft = 0;
  55981. var dashshft = 0;
  55982. var curshft = 0;
  55983. var p = 0;
  55984. var i = 0;
  55985. var j = 0;
  55986. for (i = 0; i < points.length - 1; i++) {
  55987. points[i + 1].subtractToRef(points[i], curvect);
  55988. lg += curvect.length();
  55989. }
  55990. shft = lg / nbSeg;
  55991. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55992. for (i = 0; i < points.length - 1; i++) {
  55993. points[i + 1].subtractToRef(points[i], curvect);
  55994. nb = Math.floor(curvect.length() / shft);
  55995. curvect.normalize();
  55996. j = 0;
  55997. while (j < nb && p < positions.length) {
  55998. curshft = shft * j;
  55999. positions[p] = points[i].x + curshft * curvect.x;
  56000. positions[p + 1] = points[i].y + curshft * curvect.y;
  56001. positions[p + 2] = points[i].z + curshft * curvect.z;
  56002. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56003. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56004. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56005. p += 6;
  56006. j++;
  56007. }
  56008. }
  56009. while (p < positions.length) {
  56010. positions[p] = points[i].x;
  56011. positions[p + 1] = points[i].y;
  56012. positions[p + 2] = points[i].z;
  56013. p += 3;
  56014. }
  56015. };
  56016. instance.updateMeshPositions(positionFunction, false);
  56017. return instance;
  56018. }
  56019. // dashed lines creation
  56020. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56021. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56022. vertexData.applyToMesh(dashedLines, options.updatable);
  56023. dashedLines.dashSize = dashSize;
  56024. dashedLines.gapSize = gapSize;
  56025. return dashedLines;
  56026. };
  56027. /**
  56028. * Creates an extruded shape mesh.
  56029. * 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.
  56030. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56031. *
  56032. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56033. * 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
  56034. * extruded along the Z axis.
  56035. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56036. * 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.
  56037. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56038. * 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
  56039. * 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
  56040. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56041. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56042. * 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).
  56043. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56044. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56046. */
  56047. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56048. if (scene === void 0) { scene = null; }
  56049. var path = options.path;
  56050. var shape = options.shape;
  56051. var scale = options.scale || 1;
  56052. var rotation = options.rotation || 0;
  56053. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56054. var updatable = options.updatable;
  56055. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56056. var instance = options.instance || null;
  56057. var invertUV = options.invertUV || false;
  56058. 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);
  56059. };
  56060. /**
  56061. * Creates an custom extruded shape mesh.
  56062. * 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.
  56063. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56064. *
  56065. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56066. * 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
  56067. * extruded along the Z axis.
  56068. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56069. * 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
  56070. * and the distance of this point from the begining of the path :
  56071. * ```javascript
  56072. * var rotationFunction = function(i, distance) {
  56073. * // do things
  56074. * return rotationValue; }
  56075. * ```
  56076. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56077. * 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
  56078. * and the distance of this point from the begining of the path :
  56079. * ```javascript
  56080. * var scaleFunction = function(i, distance) {
  56081. * // do things
  56082. * return scaleValue;}
  56083. * ```
  56084. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56085. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56086. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56087. * 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
  56088. * 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
  56089. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56090. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56091. * 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).
  56092. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56093. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56094. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56095. */
  56096. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56097. var path = options.path;
  56098. var shape = options.shape;
  56099. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56100. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56101. var ribbonCloseArray = options.ribbonCloseArray || false;
  56102. var ribbonClosePath = options.ribbonClosePath || false;
  56103. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56104. var updatable = options.updatable;
  56105. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56106. var instance = options.instance;
  56107. var invertUV = options.invertUV || false;
  56108. 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);
  56109. };
  56110. /**
  56111. * Creates lathe mesh.
  56112. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56113. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56114. *
  56115. * 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
  56116. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56117. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56118. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56119. * 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.
  56120. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56121. * 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
  56122. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56123. * 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).
  56124. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56125. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56126. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56127. */
  56128. MeshBuilder.CreateLathe = function (name, options, scene) {
  56129. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56130. var closed = (options.closed === undefined) ? true : options.closed;
  56131. var shape = options.shape;
  56132. var radius = options.radius || 1;
  56133. var tessellation = options.tessellation || 64;
  56134. var updatable = options.updatable;
  56135. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56136. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56137. var pi2 = Math.PI * 2;
  56138. var paths = new Array();
  56139. var invertUV = options.invertUV || false;
  56140. var i = 0;
  56141. var p = 0;
  56142. var step = pi2 / tessellation * arc;
  56143. var rotated;
  56144. var path = new Array();
  56145. ;
  56146. for (i = 0; i <= tessellation; i++) {
  56147. var path = [];
  56148. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56149. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56150. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56151. }
  56152. for (p = 0; p < shape.length; p++) {
  56153. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56154. path.push(rotated);
  56155. }
  56156. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56157. 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));
  56158. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56159. }
  56160. paths.push(path);
  56161. }
  56162. // lathe ribbon
  56163. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56164. return lathe;
  56165. };
  56166. /**
  56167. * Creates a plane mesh.
  56168. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56169. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56170. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56171. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56173. * 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).
  56174. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56175. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56176. */
  56177. MeshBuilder.CreatePlane = function (name, options, scene) {
  56178. var plane = new BABYLON.Mesh(name, scene);
  56179. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56180. plane._originalBuilderSideOrientation = options.sideOrientation;
  56181. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56182. vertexData.applyToMesh(plane, options.updatable);
  56183. if (options.sourcePlane) {
  56184. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56185. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56186. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56187. plane.rotate(vectorProduct, product);
  56188. }
  56189. return plane;
  56190. };
  56191. /**
  56192. * Creates a ground mesh.
  56193. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56194. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56195. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56196. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56197. */
  56198. MeshBuilder.CreateGround = function (name, options, scene) {
  56199. var ground = new BABYLON.GroundMesh(name, scene);
  56200. ground._setReady(false);
  56201. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56202. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56203. ground._width = options.width || 1;
  56204. ground._height = options.height || 1;
  56205. ground._maxX = ground._width / 2;
  56206. ground._maxZ = ground._height / 2;
  56207. ground._minX = -ground._maxX;
  56208. ground._minZ = -ground._maxZ;
  56209. var vertexData = BABYLON.VertexData.CreateGround(options);
  56210. vertexData.applyToMesh(ground, options.updatable);
  56211. ground._setReady(true);
  56212. return ground;
  56213. };
  56214. /**
  56215. * Creates a tiled ground mesh.
  56216. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56217. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56218. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56219. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56220. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56221. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56222. * numbers of subdivisions on the ground width and height of each tile.
  56223. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56224. */
  56225. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56226. var tiledGround = new BABYLON.Mesh(name, scene);
  56227. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56228. vertexData.applyToMesh(tiledGround, options.updatable);
  56229. return tiledGround;
  56230. };
  56231. /**
  56232. * Creates a ground mesh from a height map.
  56233. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56234. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56235. * The parameter `url` sets the URL of the height map image resource.
  56236. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56237. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56238. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56239. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56240. * 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.
  56241. * 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).
  56242. * This function is passed the newly built mesh :
  56243. * ```javascript
  56244. * function(mesh) { // do things
  56245. * return; }
  56246. * ```
  56247. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56248. */
  56249. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56250. var width = options.width || 10.0;
  56251. var height = options.height || 10.0;
  56252. var subdivisions = options.subdivisions || 1 | 0;
  56253. var minHeight = options.minHeight || 0.0;
  56254. var maxHeight = options.maxHeight || 1.0;
  56255. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56256. var updatable = options.updatable;
  56257. var onReady = options.onReady;
  56258. var ground = new BABYLON.GroundMesh(name, scene);
  56259. ground._subdivisionsX = subdivisions;
  56260. ground._subdivisionsY = subdivisions;
  56261. ground._width = width;
  56262. ground._height = height;
  56263. ground._maxX = ground._width / 2.0;
  56264. ground._maxZ = ground._height / 2.0;
  56265. ground._minX = -ground._maxX;
  56266. ground._minZ = -ground._maxZ;
  56267. ground._setReady(false);
  56268. var onload = function (img) {
  56269. // Getting height map data
  56270. var canvas = document.createElement("canvas");
  56271. var context = canvas.getContext("2d");
  56272. if (!context) {
  56273. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56274. }
  56275. if (scene.isDisposed) {
  56276. return;
  56277. }
  56278. var bufferWidth = img.width;
  56279. var bufferHeight = img.height;
  56280. canvas.width = bufferWidth;
  56281. canvas.height = bufferHeight;
  56282. context.drawImage(img, 0, 0);
  56283. // Create VertexData from map data
  56284. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56285. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56286. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56287. width: width, height: height,
  56288. subdivisions: subdivisions,
  56289. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56290. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56291. });
  56292. vertexData.applyToMesh(ground, updatable);
  56293. ground._setReady(true);
  56294. //execute ready callback, if set
  56295. if (onReady) {
  56296. onReady(ground);
  56297. }
  56298. };
  56299. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56300. return ground;
  56301. };
  56302. /**
  56303. * Creates a polygon mesh.
  56304. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56305. * 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.
  56306. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56308. * 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).
  56309. * Remember you can only change the shape positions, not their number when updating a polygon.
  56310. */
  56311. MeshBuilder.CreatePolygon = function (name, options, scene) {
  56312. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56313. var shape = options.shape;
  56314. var holes = options.holes || [];
  56315. var depth = options.depth || 0;
  56316. var contours = [];
  56317. var hole = [];
  56318. for (var i = 0; i < shape.length; i++) {
  56319. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  56320. }
  56321. var epsilon = 0.00000001;
  56322. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  56323. contours.pop();
  56324. }
  56325. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  56326. for (var hNb = 0; hNb < holes.length; hNb++) {
  56327. hole = [];
  56328. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56329. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56330. }
  56331. polygonTriangulation.addHole(hole);
  56332. }
  56333. var polygon = polygonTriangulation.build(options.updatable, depth);
  56334. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56335. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56336. vertexData.applyToMesh(polygon, options.updatable);
  56337. return polygon;
  56338. };
  56339. ;
  56340. /**
  56341. * Creates an extruded polygon mesh, with depth in the Y direction.
  56342. * 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).
  56343. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56344. */
  56345. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56346. return MeshBuilder.CreatePolygon(name, options, scene);
  56347. };
  56348. ;
  56349. /**
  56350. * Creates a tube mesh.
  56351. * 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.
  56352. *
  56353. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56354. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56355. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56356. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56357. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56358. * 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.
  56359. * It must return a radius value (positive float) :
  56360. * ```javascript
  56361. * var radiusFunction = function(i, distance) {
  56362. * // do things
  56363. * return radius; }
  56364. * ```
  56365. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56366. * 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
  56367. * 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
  56368. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56369. * 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).
  56370. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56371. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56372. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56373. */
  56374. MeshBuilder.CreateTube = function (name, options, scene) {
  56375. var path = options.path;
  56376. var instance = options.instance;
  56377. var radius = 1.0;
  56378. if (instance) {
  56379. radius = instance.radius;
  56380. }
  56381. if (options.radius !== undefined) {
  56382. radius = options.radius;
  56383. }
  56384. ;
  56385. var tessellation = options.tessellation || 64 | 0;
  56386. var radiusFunction = options.radiusFunction || null;
  56387. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56388. var invertUV = options.invertUV || false;
  56389. var updatable = options.updatable;
  56390. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56391. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56392. // tube geometry
  56393. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56394. var tangents = path3D.getTangents();
  56395. var normals = path3D.getNormals();
  56396. var distances = path3D.getDistances();
  56397. var pi2 = Math.PI * 2;
  56398. var step = pi2 / tessellation * arc;
  56399. var returnRadius = function () { return radius; };
  56400. var radiusFunctionFinal = radiusFunction || returnRadius;
  56401. var circlePath;
  56402. var rad;
  56403. var normal;
  56404. var rotated;
  56405. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56406. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56407. for (var i = 0; i < path.length; i++) {
  56408. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56409. circlePath = Array(); // current circle array
  56410. normal = normals[i]; // current normal
  56411. for (var t = 0; t < tessellation; t++) {
  56412. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56413. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56414. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56415. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56416. circlePath[t] = rotated;
  56417. }
  56418. circlePaths[index] = circlePath;
  56419. index++;
  56420. }
  56421. // cap
  56422. var capPath = function (nbPoints, pathIndex) {
  56423. var pointCap = Array();
  56424. for (var i = 0; i < nbPoints; i++) {
  56425. pointCap.push(path[pathIndex]);
  56426. }
  56427. return pointCap;
  56428. };
  56429. switch (cap) {
  56430. case BABYLON.Mesh.NO_CAP:
  56431. break;
  56432. case BABYLON.Mesh.CAP_START:
  56433. circlePaths[0] = capPath(tessellation, 0);
  56434. circlePaths[1] = circlePaths[2].slice(0);
  56435. break;
  56436. case BABYLON.Mesh.CAP_END:
  56437. circlePaths[index] = circlePaths[index - 1].slice(0);
  56438. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56439. break;
  56440. case BABYLON.Mesh.CAP_ALL:
  56441. circlePaths[0] = capPath(tessellation, 0);
  56442. circlePaths[1] = circlePaths[2].slice(0);
  56443. circlePaths[index] = circlePaths[index - 1].slice(0);
  56444. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56445. break;
  56446. default:
  56447. break;
  56448. }
  56449. return circlePaths;
  56450. };
  56451. var path3D;
  56452. var pathArray;
  56453. if (instance) {
  56454. var arc = options.arc || instance.arc;
  56455. path3D = (instance.path3D).update(path);
  56456. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56457. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56458. instance.path3D = path3D;
  56459. instance.pathArray = pathArray;
  56460. instance.arc = arc;
  56461. instance.radius = radius;
  56462. return instance;
  56463. }
  56464. // tube creation
  56465. path3D = new BABYLON.Path3D(path);
  56466. var newPathArray = new Array();
  56467. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56468. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56469. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56470. tube.pathArray = pathArray;
  56471. tube.path3D = path3D;
  56472. tube.tessellation = tessellation;
  56473. tube.cap = cap;
  56474. tube.arc = options.arc;
  56475. tube.radius = radius;
  56476. return tube;
  56477. };
  56478. /**
  56479. * Creates a polyhedron mesh.
  56480. *
  56481. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56482. * 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
  56483. * to choose the wanted type.
  56484. * The parameter `size` (positive float, default 1) sets the polygon size.
  56485. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56486. * 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`.
  56487. * 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
  56488. * 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)`).
  56489. * 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
  56490. * 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.
  56491. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56492. * 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).
  56493. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56494. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56495. */
  56496. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56497. var polyhedron = new BABYLON.Mesh(name, scene);
  56498. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56499. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56500. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56501. vertexData.applyToMesh(polyhedron, options.updatable);
  56502. return polyhedron;
  56503. };
  56504. /**
  56505. * Creates a decal mesh.
  56506. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56507. * 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.
  56508. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56509. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56510. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56511. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56512. */
  56513. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56514. var indices = sourceMesh.getIndices();
  56515. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56516. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56517. var position = options.position || BABYLON.Vector3.Zero();
  56518. var normal = options.normal || BABYLON.Vector3.Up();
  56519. var size = options.size || BABYLON.Vector3.One();
  56520. var angle = options.angle || 0;
  56521. // Getting correct rotation
  56522. if (!normal) {
  56523. var target = new BABYLON.Vector3(0, 0, 1);
  56524. var camera = sourceMesh.getScene().activeCamera;
  56525. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56526. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56527. }
  56528. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56529. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56530. var pitch = Math.atan2(normal.y, len);
  56531. // Matrix
  56532. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56533. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56534. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56535. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56536. var vertexData = new BABYLON.VertexData();
  56537. vertexData.indices = [];
  56538. vertexData.positions = [];
  56539. vertexData.normals = [];
  56540. vertexData.uvs = [];
  56541. var currentVertexDataIndex = 0;
  56542. var extractDecalVector3 = function (indexId) {
  56543. var result = new BABYLON.PositionNormalVertex();
  56544. if (!indices || !positions || !normals) {
  56545. return result;
  56546. }
  56547. var vertexId = indices[indexId];
  56548. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  56549. // Send vector to decal local world
  56550. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  56551. // Get normal
  56552. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  56553. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  56554. return result;
  56555. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  56556. var clip = function (vertices, axis) {
  56557. if (vertices.length === 0) {
  56558. return vertices;
  56559. }
  56560. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  56561. var clipVertices = function (v0, v1) {
  56562. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  56563. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  56564. };
  56565. var result = new Array();
  56566. for (var index = 0; index < vertices.length; index += 3) {
  56567. var v1Out;
  56568. var v2Out;
  56569. var v3Out;
  56570. var total = 0;
  56571. var nV1 = null;
  56572. var nV2 = null;
  56573. var nV3 = null;
  56574. var nV4 = null;
  56575. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  56576. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  56577. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  56578. v1Out = d1 > 0;
  56579. v2Out = d2 > 0;
  56580. v3Out = d3 > 0;
  56581. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  56582. switch (total) {
  56583. case 0:
  56584. result.push(vertices[index]);
  56585. result.push(vertices[index + 1]);
  56586. result.push(vertices[index + 2]);
  56587. break;
  56588. case 1:
  56589. if (v1Out) {
  56590. nV1 = vertices[index + 1];
  56591. nV2 = vertices[index + 2];
  56592. nV3 = clipVertices(vertices[index], nV1);
  56593. nV4 = clipVertices(vertices[index], nV2);
  56594. }
  56595. if (v2Out) {
  56596. nV1 = vertices[index];
  56597. nV2 = vertices[index + 2];
  56598. nV3 = clipVertices(vertices[index + 1], nV1);
  56599. nV4 = clipVertices(vertices[index + 1], nV2);
  56600. result.push(nV3);
  56601. result.push(nV2.clone());
  56602. result.push(nV1.clone());
  56603. result.push(nV2.clone());
  56604. result.push(nV3.clone());
  56605. result.push(nV4);
  56606. break;
  56607. }
  56608. if (v3Out) {
  56609. nV1 = vertices[index];
  56610. nV2 = vertices[index + 1];
  56611. nV3 = clipVertices(vertices[index + 2], nV1);
  56612. nV4 = clipVertices(vertices[index + 2], nV2);
  56613. }
  56614. if (nV1 && nV2 && nV3 && nV4) {
  56615. result.push(nV1.clone());
  56616. result.push(nV2.clone());
  56617. result.push(nV3);
  56618. result.push(nV4);
  56619. result.push(nV3.clone());
  56620. result.push(nV2.clone());
  56621. }
  56622. break;
  56623. case 2:
  56624. if (!v1Out) {
  56625. nV1 = vertices[index].clone();
  56626. nV2 = clipVertices(nV1, vertices[index + 1]);
  56627. nV3 = clipVertices(nV1, vertices[index + 2]);
  56628. result.push(nV1);
  56629. result.push(nV2);
  56630. result.push(nV3);
  56631. }
  56632. if (!v2Out) {
  56633. nV1 = vertices[index + 1].clone();
  56634. nV2 = clipVertices(nV1, vertices[index + 2]);
  56635. nV3 = clipVertices(nV1, vertices[index]);
  56636. result.push(nV1);
  56637. result.push(nV2);
  56638. result.push(nV3);
  56639. }
  56640. if (!v3Out) {
  56641. nV1 = vertices[index + 2].clone();
  56642. nV2 = clipVertices(nV1, vertices[index]);
  56643. nV3 = clipVertices(nV1, vertices[index + 1]);
  56644. result.push(nV1);
  56645. result.push(nV2);
  56646. result.push(nV3);
  56647. }
  56648. break;
  56649. case 3:
  56650. break;
  56651. }
  56652. }
  56653. return result;
  56654. };
  56655. for (var index = 0; index < indices.length; index += 3) {
  56656. var faceVertices = new Array();
  56657. faceVertices.push(extractDecalVector3(index));
  56658. faceVertices.push(extractDecalVector3(index + 1));
  56659. faceVertices.push(extractDecalVector3(index + 2));
  56660. // Clip
  56661. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  56662. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  56663. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  56664. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  56665. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  56666. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  56667. if (faceVertices.length === 0) {
  56668. continue;
  56669. }
  56670. // Add UVs and get back to world
  56671. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  56672. var vertex = faceVertices[vIndex];
  56673. //TODO check for Int32Array | Uint32Array | Uint16Array
  56674. vertexData.indices.push(currentVertexDataIndex);
  56675. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  56676. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  56677. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  56678. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56679. currentVertexDataIndex++;
  56680. }
  56681. }
  56682. // Return mesh
  56683. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56684. vertexData.applyToMesh(decal);
  56685. decal.position = position.clone();
  56686. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56687. return decal;
  56688. };
  56689. // Privates
  56690. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56691. // extrusion geometry
  56692. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56693. var tangents = path3D.getTangents();
  56694. var normals = path3D.getNormals();
  56695. var binormals = path3D.getBinormals();
  56696. var distances = path3D.getDistances();
  56697. var angle = 0;
  56698. var returnScale = function () { return scale !== null ? scale : 1; };
  56699. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56700. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56701. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56702. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56703. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56704. for (var i = 0; i < curve.length; i++) {
  56705. var shapePath = new Array();
  56706. var angleStep = rotate(i, distances[i]);
  56707. var scaleRatio = scl(i, distances[i]);
  56708. for (var p = 0; p < shape.length; p++) {
  56709. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56710. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56711. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56712. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56713. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56714. shapePath[p] = rotated;
  56715. }
  56716. shapePaths[index] = shapePath;
  56717. angle += angleStep;
  56718. index++;
  56719. }
  56720. // cap
  56721. var capPath = function (shapePath) {
  56722. var pointCap = Array();
  56723. var barycenter = BABYLON.Vector3.Zero();
  56724. var i;
  56725. for (i = 0; i < shapePath.length; i++) {
  56726. barycenter.addInPlace(shapePath[i]);
  56727. }
  56728. barycenter.scaleInPlace(1.0 / shapePath.length);
  56729. for (i = 0; i < shapePath.length; i++) {
  56730. pointCap.push(barycenter);
  56731. }
  56732. return pointCap;
  56733. };
  56734. switch (cap) {
  56735. case BABYLON.Mesh.NO_CAP:
  56736. break;
  56737. case BABYLON.Mesh.CAP_START:
  56738. shapePaths[0] = capPath(shapePaths[2]);
  56739. shapePaths[1] = shapePaths[2];
  56740. break;
  56741. case BABYLON.Mesh.CAP_END:
  56742. shapePaths[index] = shapePaths[index - 1];
  56743. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56744. break;
  56745. case BABYLON.Mesh.CAP_ALL:
  56746. shapePaths[0] = capPath(shapePaths[2]);
  56747. shapePaths[1] = shapePaths[2];
  56748. shapePaths[index] = shapePaths[index - 1];
  56749. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56750. break;
  56751. default:
  56752. break;
  56753. }
  56754. return shapePaths;
  56755. };
  56756. var path3D;
  56757. var pathArray;
  56758. if (instance) {
  56759. path3D = (instance.path3D).update(curve);
  56760. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56761. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56762. return instance;
  56763. }
  56764. // extruded shape creation
  56765. path3D = new BABYLON.Path3D(curve);
  56766. var newShapePaths = new Array();
  56767. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56768. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56769. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56770. extrudedGeneric.pathArray = pathArray;
  56771. extrudedGeneric.path3D = path3D;
  56772. extrudedGeneric.cap = cap;
  56773. return extrudedGeneric;
  56774. };
  56775. return MeshBuilder;
  56776. }());
  56777. BABYLON.MeshBuilder = MeshBuilder;
  56778. })(BABYLON || (BABYLON = {}));
  56779. //# sourceMappingURL=babylon.meshBuilder.js.map
  56780. var BABYLON;
  56781. (function (BABYLON) {
  56782. /**
  56783. * Draco compression (https://google.github.io/draco/)
  56784. */
  56785. var DracoCompression = /** @class */ (function () {
  56786. /**
  56787. * Constructor
  56788. * @param numWorkers The number of workers for async operations
  56789. */
  56790. function DracoCompression(numWorkers) {
  56791. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56792. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56793. if (!workerBlobUrl || !Worker) {
  56794. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56795. return;
  56796. }
  56797. var workers = new Array(numWorkers);
  56798. for (var i = 0; i < workers.length; i++) {
  56799. var worker = new Worker(workerBlobUrl);
  56800. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56801. workers[i] = worker;
  56802. }
  56803. this._workerPool = new BABYLON.WorkerPool(workers);
  56804. }
  56805. /**
  56806. * Stop all async operations and release resources.
  56807. */
  56808. DracoCompression.prototype.dispose = function () {
  56809. this._workerPool.dispose();
  56810. delete this._workerPool;
  56811. };
  56812. /**
  56813. * Decode Draco compressed mesh data to vertex data.
  56814. * @param data The array buffer view for the Draco compression data
  56815. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56816. * @returns A promise that resolves with the decoded vertex data
  56817. */
  56818. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56819. var _this = this;
  56820. return new Promise(function (resolve, reject) {
  56821. _this._workerPool.push(function (worker, onComplete) {
  56822. var vertexData = new BABYLON.VertexData();
  56823. var onError = function (error) {
  56824. worker.removeEventListener("error", onError);
  56825. worker.removeEventListener("message", onMessage);
  56826. reject(error);
  56827. onComplete();
  56828. };
  56829. var onMessage = function (message) {
  56830. if (message.data === "done") {
  56831. worker.removeEventListener("error", onError);
  56832. worker.removeEventListener("message", onMessage);
  56833. resolve(vertexData);
  56834. onComplete();
  56835. }
  56836. else if (message.data.id === "indices") {
  56837. vertexData.indices = message.data.value;
  56838. }
  56839. else {
  56840. vertexData.set(message.data.value, message.data.id);
  56841. }
  56842. };
  56843. worker.addEventListener("error", onError);
  56844. worker.addEventListener("message", onMessage);
  56845. var dataCopy = new Uint8Array(data.byteLength);
  56846. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56847. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56848. });
  56849. });
  56850. };
  56851. /**
  56852. * The worker function that gets converted to a blob url to pass into a worker.
  56853. */
  56854. DracoCompression._Worker = function () {
  56855. // self is actually a DedicatedWorkerGlobalScope
  56856. var _self = self;
  56857. var decodeMesh = function (data, attributes) {
  56858. var dracoModule = new DracoDecoderModule();
  56859. var buffer = new dracoModule.DecoderBuffer();
  56860. buffer.Init(data, data.byteLength);
  56861. var decoder = new dracoModule.Decoder();
  56862. var geometry;
  56863. var status;
  56864. try {
  56865. var type = decoder.GetEncodedGeometryType(buffer);
  56866. switch (type) {
  56867. case dracoModule.TRIANGULAR_MESH:
  56868. geometry = new dracoModule.Mesh();
  56869. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56870. break;
  56871. case dracoModule.POINT_CLOUD:
  56872. geometry = new dracoModule.PointCloud();
  56873. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56874. break;
  56875. default:
  56876. throw new Error("Invalid geometry type " + type);
  56877. }
  56878. if (!status.ok() || !geometry.ptr) {
  56879. throw new Error(status.error_msg());
  56880. }
  56881. var numPoints = geometry.num_points();
  56882. if (type === dracoModule.TRIANGULAR_MESH) {
  56883. var numFaces = geometry.num_faces();
  56884. var faceIndices = new dracoModule.DracoInt32Array();
  56885. try {
  56886. var indices = new Uint32Array(numFaces * 3);
  56887. for (var i = 0; i < numFaces; i++) {
  56888. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56889. var offset = i * 3;
  56890. indices[offset + 0] = faceIndices.GetValue(0);
  56891. indices[offset + 1] = faceIndices.GetValue(1);
  56892. indices[offset + 2] = faceIndices.GetValue(2);
  56893. }
  56894. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56895. }
  56896. finally {
  56897. dracoModule.destroy(faceIndices);
  56898. }
  56899. }
  56900. for (var kind in attributes) {
  56901. var uniqueId = attributes[kind];
  56902. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56903. var dracoData = new dracoModule.DracoFloat32Array();
  56904. try {
  56905. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56906. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56907. for (var i = 0; i < babylonData.length; i++) {
  56908. babylonData[i] = dracoData.GetValue(i);
  56909. }
  56910. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56911. }
  56912. finally {
  56913. dracoModule.destroy(dracoData);
  56914. }
  56915. }
  56916. }
  56917. finally {
  56918. if (geometry) {
  56919. dracoModule.destroy(geometry);
  56920. }
  56921. dracoModule.destroy(decoder);
  56922. dracoModule.destroy(buffer);
  56923. }
  56924. _self.postMessage("done");
  56925. };
  56926. _self.onmessage = function (event) {
  56927. switch (event.data.id) {
  56928. case "initDecoder": {
  56929. importScripts(event.data.url);
  56930. break;
  56931. }
  56932. case "decodeMesh": {
  56933. decodeMesh(event.data.data, event.data.attributes);
  56934. break;
  56935. }
  56936. }
  56937. };
  56938. };
  56939. DracoCompression._GetDefaultDecoderUrl = function () {
  56940. if (!BABYLON.Tools.IsWindowObjectExist) {
  56941. return null;
  56942. }
  56943. for (var i = 0; i < document.scripts.length; i++) {
  56944. if (document.scripts[i].type === "text/x-draco-decoder") {
  56945. return document.scripts[i].src;
  56946. }
  56947. }
  56948. return null;
  56949. };
  56950. /**
  56951. * Gets the url to the draco decoder if available.
  56952. */
  56953. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56954. return DracoCompression;
  56955. }());
  56956. BABYLON.DracoCompression = DracoCompression;
  56957. })(BABYLON || (BABYLON = {}));
  56958. //# sourceMappingURL=babylon.dracoCompression.js.map
  56959. var BABYLON;
  56960. (function (BABYLON) {
  56961. var AudioEngine = /** @class */ (function () {
  56962. function AudioEngine() {
  56963. this._audioContext = null;
  56964. this._audioContextInitialized = false;
  56965. this.canUseWebAudio = false;
  56966. this.WarnedWebAudioUnsupported = false;
  56967. this.unlocked = false;
  56968. this.isMP3supported = false;
  56969. this.isOGGsupported = false;
  56970. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56971. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56972. this.canUseWebAudio = true;
  56973. }
  56974. var audioElem = document.createElement('audio');
  56975. try {
  56976. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56977. this.isMP3supported = true;
  56978. }
  56979. }
  56980. catch (e) {
  56981. // protect error during capability check.
  56982. }
  56983. try {
  56984. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56985. this.isOGGsupported = true;
  56986. }
  56987. }
  56988. catch (e) {
  56989. // protect error during capability check.
  56990. }
  56991. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56992. this._unlockiOSaudio();
  56993. }
  56994. else {
  56995. this.unlocked = true;
  56996. }
  56997. }
  56998. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56999. get: function () {
  57000. if (!this._audioContextInitialized) {
  57001. this._initializeAudioContext();
  57002. }
  57003. return this._audioContext;
  57004. },
  57005. enumerable: true,
  57006. configurable: true
  57007. });
  57008. AudioEngine.prototype._unlockiOSaudio = function () {
  57009. var _this = this;
  57010. var unlockaudio = function () {
  57011. if (!_this.audioContext) {
  57012. return;
  57013. }
  57014. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57015. var source = _this.audioContext.createBufferSource();
  57016. source.buffer = buffer;
  57017. source.connect(_this.audioContext.destination);
  57018. source.start(0);
  57019. setTimeout(function () {
  57020. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57021. _this.unlocked = true;
  57022. window.removeEventListener('touchend', unlockaudio, false);
  57023. if (_this.onAudioUnlocked) {
  57024. _this.onAudioUnlocked();
  57025. }
  57026. }
  57027. }, 0);
  57028. };
  57029. window.addEventListener('touchend', unlockaudio, false);
  57030. };
  57031. AudioEngine.prototype._initializeAudioContext = function () {
  57032. try {
  57033. if (this.canUseWebAudio) {
  57034. this._audioContext = new AudioContext();
  57035. // create a global volume gain node
  57036. this.masterGain = this._audioContext.createGain();
  57037. this.masterGain.gain.value = 1;
  57038. this.masterGain.connect(this._audioContext.destination);
  57039. this._audioContextInitialized = true;
  57040. }
  57041. }
  57042. catch (e) {
  57043. this.canUseWebAudio = false;
  57044. BABYLON.Tools.Error("Web Audio: " + e.message);
  57045. }
  57046. };
  57047. AudioEngine.prototype.dispose = function () {
  57048. if (this.canUseWebAudio && this._audioContextInitialized) {
  57049. if (this._connectedAnalyser && this._audioContext) {
  57050. this._connectedAnalyser.stopDebugCanvas();
  57051. this._connectedAnalyser.dispose();
  57052. this.masterGain.disconnect();
  57053. this.masterGain.connect(this._audioContext.destination);
  57054. this._connectedAnalyser = null;
  57055. }
  57056. this.masterGain.gain.value = 1;
  57057. }
  57058. this.WarnedWebAudioUnsupported = false;
  57059. };
  57060. AudioEngine.prototype.getGlobalVolume = function () {
  57061. if (this.canUseWebAudio && this._audioContextInitialized) {
  57062. return this.masterGain.gain.value;
  57063. }
  57064. else {
  57065. return -1;
  57066. }
  57067. };
  57068. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57069. if (this.canUseWebAudio && this._audioContextInitialized) {
  57070. this.masterGain.gain.value = newVolume;
  57071. }
  57072. };
  57073. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57074. if (this._connectedAnalyser) {
  57075. this._connectedAnalyser.stopDebugCanvas();
  57076. }
  57077. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57078. this._connectedAnalyser = analyser;
  57079. this.masterGain.disconnect();
  57080. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57081. }
  57082. };
  57083. return AudioEngine;
  57084. }());
  57085. BABYLON.AudioEngine = AudioEngine;
  57086. })(BABYLON || (BABYLON = {}));
  57087. //# sourceMappingURL=babylon.audioEngine.js.map
  57088. var BABYLON;
  57089. (function (BABYLON) {
  57090. var Sound = /** @class */ (function () {
  57091. /**
  57092. * Create a sound and attach it to a scene
  57093. * @param name Name of your sound
  57094. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57095. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57096. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57097. */
  57098. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57099. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57100. var _this = this;
  57101. this.autoplay = false;
  57102. this.loop = false;
  57103. this.useCustomAttenuation = false;
  57104. this.spatialSound = false;
  57105. this.refDistance = 1;
  57106. this.rolloffFactor = 1;
  57107. this.maxDistance = 100;
  57108. this.distanceModel = "linear";
  57109. this._panningModel = "equalpower";
  57110. this._playbackRate = 1;
  57111. this._streaming = false;
  57112. this._startTime = 0;
  57113. this._startOffset = 0;
  57114. this._position = BABYLON.Vector3.Zero();
  57115. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57116. this._volume = 1;
  57117. this._isReadyToPlay = false;
  57118. this.isPlaying = false;
  57119. this.isPaused = false;
  57120. this._isDirectional = false;
  57121. // Used if you'd like to create a directional sound.
  57122. // If not set, the sound will be omnidirectional
  57123. this._coneInnerAngle = 360;
  57124. this._coneOuterAngle = 360;
  57125. this._coneOuterGain = 0;
  57126. this._isOutputConnected = false;
  57127. this._urlType = "Unknown";
  57128. this.name = name;
  57129. this._scene = scene;
  57130. this._readyToPlayCallback = readyToPlayCallback;
  57131. // Default custom attenuation function is a linear attenuation
  57132. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57133. if (currentDistance < maxDistance) {
  57134. return currentVolume * (1 - currentDistance / maxDistance);
  57135. }
  57136. else {
  57137. return 0;
  57138. }
  57139. };
  57140. if (options) {
  57141. this.autoplay = options.autoplay || false;
  57142. this.loop = options.loop || false;
  57143. // if volume === 0, we need another way to check this option
  57144. if (options.volume !== undefined) {
  57145. this._volume = options.volume;
  57146. }
  57147. this.spatialSound = options.spatialSound || false;
  57148. this.maxDistance = options.maxDistance || 100;
  57149. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57150. this.rolloffFactor = options.rolloffFactor || 1;
  57151. this.refDistance = options.refDistance || 1;
  57152. this.distanceModel = options.distanceModel || "linear";
  57153. this._playbackRate = options.playbackRate || 1;
  57154. this._streaming = options.streaming || false;
  57155. }
  57156. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57157. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57158. this._soundGain.gain.value = this._volume;
  57159. this._inputAudioNode = this._soundGain;
  57160. this._ouputAudioNode = this._soundGain;
  57161. if (this.spatialSound) {
  57162. this._createSpatialParameters();
  57163. }
  57164. this._scene.mainSoundTrack.AddSound(this);
  57165. var validParameter = true;
  57166. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57167. if (urlOrArrayBuffer) {
  57168. if (typeof (urlOrArrayBuffer) === "string")
  57169. this._urlType = "String";
  57170. if (Array.isArray(urlOrArrayBuffer))
  57171. this._urlType = "Array";
  57172. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57173. this._urlType = "ArrayBuffer";
  57174. var urls = [];
  57175. var codecSupportedFound = false;
  57176. switch (this._urlType) {
  57177. case "ArrayBuffer":
  57178. if (urlOrArrayBuffer.byteLength > 0) {
  57179. codecSupportedFound = true;
  57180. this._soundLoaded(urlOrArrayBuffer);
  57181. }
  57182. break;
  57183. case "String":
  57184. urls.push(urlOrArrayBuffer);
  57185. case "Array":
  57186. if (urls.length === 0)
  57187. urls = urlOrArrayBuffer;
  57188. // If we found a supported format, we load it immediately and stop the loop
  57189. for (var i = 0; i < urls.length; i++) {
  57190. var url = urls[i];
  57191. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57192. codecSupportedFound = true;
  57193. }
  57194. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57195. codecSupportedFound = true;
  57196. }
  57197. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57198. codecSupportedFound = true;
  57199. }
  57200. if (url.indexOf("blob:") !== -1) {
  57201. codecSupportedFound = true;
  57202. }
  57203. if (codecSupportedFound) {
  57204. // Loading sound using XHR2
  57205. if (!this._streaming) {
  57206. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57207. }
  57208. else {
  57209. this._htmlAudioElement = new Audio(url);
  57210. this._htmlAudioElement.controls = false;
  57211. this._htmlAudioElement.loop = this.loop;
  57212. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57213. this._htmlAudioElement.preload = "auto";
  57214. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57215. _this._isReadyToPlay = true;
  57216. if (_this.autoplay) {
  57217. _this.play();
  57218. }
  57219. if (_this._readyToPlayCallback) {
  57220. _this._readyToPlayCallback();
  57221. }
  57222. });
  57223. document.body.appendChild(this._htmlAudioElement);
  57224. }
  57225. break;
  57226. }
  57227. }
  57228. break;
  57229. default:
  57230. validParameter = false;
  57231. break;
  57232. }
  57233. if (!validParameter) {
  57234. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57235. }
  57236. else {
  57237. if (!codecSupportedFound) {
  57238. this._isReadyToPlay = true;
  57239. // Simulating a ready to play event to avoid breaking code path
  57240. if (this._readyToPlayCallback) {
  57241. window.setTimeout(function () {
  57242. if (_this._readyToPlayCallback) {
  57243. _this._readyToPlayCallback();
  57244. }
  57245. }, 1000);
  57246. }
  57247. }
  57248. }
  57249. }
  57250. }
  57251. else {
  57252. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57253. this._scene.mainSoundTrack.AddSound(this);
  57254. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57255. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57256. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57257. }
  57258. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57259. if (this._readyToPlayCallback) {
  57260. window.setTimeout(function () {
  57261. if (_this._readyToPlayCallback) {
  57262. _this._readyToPlayCallback();
  57263. }
  57264. }, 1000);
  57265. }
  57266. }
  57267. }
  57268. Sound.prototype.dispose = function () {
  57269. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57270. if (this.isPlaying) {
  57271. this.stop();
  57272. }
  57273. this._isReadyToPlay = false;
  57274. if (this.soundTrackId === -1) {
  57275. this._scene.mainSoundTrack.RemoveSound(this);
  57276. }
  57277. else {
  57278. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57279. }
  57280. if (this._soundGain) {
  57281. this._soundGain.disconnect();
  57282. this._soundGain = null;
  57283. }
  57284. if (this._soundPanner) {
  57285. this._soundPanner.disconnect();
  57286. this._soundPanner = null;
  57287. }
  57288. if (this._soundSource) {
  57289. this._soundSource.disconnect();
  57290. this._soundSource = null;
  57291. }
  57292. this._audioBuffer = null;
  57293. if (this._htmlAudioElement) {
  57294. this._htmlAudioElement.pause();
  57295. this._htmlAudioElement.src = "";
  57296. document.body.removeChild(this._htmlAudioElement);
  57297. }
  57298. if (this._connectedMesh && this._registerFunc) {
  57299. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57300. this._connectedMesh = null;
  57301. }
  57302. }
  57303. };
  57304. Sound.prototype.isReady = function () {
  57305. return this._isReadyToPlay;
  57306. };
  57307. Sound.prototype._soundLoaded = function (audioData) {
  57308. var _this = this;
  57309. if (!BABYLON.Engine.audioEngine.audioContext) {
  57310. return;
  57311. }
  57312. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  57313. _this._audioBuffer = buffer;
  57314. _this._isReadyToPlay = true;
  57315. if (_this.autoplay) {
  57316. _this.play();
  57317. }
  57318. if (_this._readyToPlayCallback) {
  57319. _this._readyToPlayCallback();
  57320. }
  57321. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  57322. };
  57323. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  57324. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57325. this._audioBuffer = audioBuffer;
  57326. this._isReadyToPlay = true;
  57327. }
  57328. };
  57329. Sound.prototype.updateOptions = function (options) {
  57330. if (options) {
  57331. this.loop = options.loop || this.loop;
  57332. this.maxDistance = options.maxDistance || this.maxDistance;
  57333. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  57334. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57335. this.refDistance = options.refDistance || this.refDistance;
  57336. this.distanceModel = options.distanceModel || this.distanceModel;
  57337. this._playbackRate = options.playbackRate || this._playbackRate;
  57338. this._updateSpatialParameters();
  57339. if (this.isPlaying) {
  57340. if (this._streaming) {
  57341. this._htmlAudioElement.playbackRate = this._playbackRate;
  57342. }
  57343. else {
  57344. if (this._soundSource) {
  57345. this._soundSource.playbackRate.value = this._playbackRate;
  57346. }
  57347. }
  57348. }
  57349. }
  57350. };
  57351. Sound.prototype._createSpatialParameters = function () {
  57352. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57353. if (this._scene.headphone) {
  57354. this._panningModel = "HRTF";
  57355. }
  57356. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57357. this._updateSpatialParameters();
  57358. this._soundPanner.connect(this._ouputAudioNode);
  57359. this._inputAudioNode = this._soundPanner;
  57360. }
  57361. };
  57362. Sound.prototype._updateSpatialParameters = function () {
  57363. if (this.spatialSound && this._soundPanner) {
  57364. if (this.useCustomAttenuation) {
  57365. // Tricks to disable in a way embedded Web Audio attenuation
  57366. this._soundPanner.distanceModel = "linear";
  57367. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57368. this._soundPanner.refDistance = 1;
  57369. this._soundPanner.rolloffFactor = 1;
  57370. this._soundPanner.panningModel = this._panningModel;
  57371. }
  57372. else {
  57373. this._soundPanner.distanceModel = this.distanceModel;
  57374. this._soundPanner.maxDistance = this.maxDistance;
  57375. this._soundPanner.refDistance = this.refDistance;
  57376. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57377. this._soundPanner.panningModel = this._panningModel;
  57378. }
  57379. }
  57380. };
  57381. Sound.prototype.switchPanningModelToHRTF = function () {
  57382. this._panningModel = "HRTF";
  57383. this._switchPanningModel();
  57384. };
  57385. Sound.prototype.switchPanningModelToEqualPower = function () {
  57386. this._panningModel = "equalpower";
  57387. this._switchPanningModel();
  57388. };
  57389. Sound.prototype._switchPanningModel = function () {
  57390. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57391. this._soundPanner.panningModel = this._panningModel;
  57392. }
  57393. };
  57394. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57395. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57396. if (this._isOutputConnected) {
  57397. this._ouputAudioNode.disconnect();
  57398. }
  57399. this._ouputAudioNode.connect(soundTrackAudioNode);
  57400. this._isOutputConnected = true;
  57401. }
  57402. };
  57403. /**
  57404. * Transform this sound into a directional source
  57405. * @param coneInnerAngle Size of the inner cone in degree
  57406. * @param coneOuterAngle Size of the outer cone in degree
  57407. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57408. */
  57409. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57410. if (coneOuterAngle < coneInnerAngle) {
  57411. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57412. return;
  57413. }
  57414. this._coneInnerAngle = coneInnerAngle;
  57415. this._coneOuterAngle = coneOuterAngle;
  57416. this._coneOuterGain = coneOuterGain;
  57417. this._isDirectional = true;
  57418. if (this.isPlaying && this.loop) {
  57419. this.stop();
  57420. this.play();
  57421. }
  57422. };
  57423. Sound.prototype.setPosition = function (newPosition) {
  57424. this._position = newPosition;
  57425. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57426. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57427. }
  57428. };
  57429. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57430. this._localDirection = newLocalDirection;
  57431. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57432. this._updateDirection();
  57433. }
  57434. };
  57435. Sound.prototype._updateDirection = function () {
  57436. if (!this._connectedMesh || !this._soundPanner) {
  57437. return;
  57438. }
  57439. var mat = this._connectedMesh.getWorldMatrix();
  57440. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57441. direction.normalize();
  57442. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57443. };
  57444. Sound.prototype.updateDistanceFromListener = function () {
  57445. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57446. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57447. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57448. }
  57449. };
  57450. Sound.prototype.setAttenuationFunction = function (callback) {
  57451. this._customAttenuationFunction = callback;
  57452. };
  57453. /**
  57454. * Play the sound
  57455. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57456. * @param offset (optional) Start the sound setting it at a specific time
  57457. */
  57458. Sound.prototype.play = function (time, offset) {
  57459. var _this = this;
  57460. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57461. try {
  57462. if (this._startOffset < 0) {
  57463. time = -this._startOffset;
  57464. this._startOffset = 0;
  57465. }
  57466. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57467. if (!this._soundSource || !this._streamingSource) {
  57468. if (this.spatialSound && this._soundPanner) {
  57469. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57470. if (this._isDirectional) {
  57471. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57472. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57473. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57474. if (this._connectedMesh) {
  57475. this._updateDirection();
  57476. }
  57477. else {
  57478. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57479. }
  57480. }
  57481. }
  57482. }
  57483. if (this._streaming) {
  57484. if (!this._streamingSource) {
  57485. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57486. this._htmlAudioElement.onended = function () { _this._onended(); };
  57487. this._htmlAudioElement.playbackRate = this._playbackRate;
  57488. }
  57489. this._streamingSource.disconnect();
  57490. this._streamingSource.connect(this._inputAudioNode);
  57491. this._htmlAudioElement.play();
  57492. }
  57493. else {
  57494. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57495. this._soundSource.buffer = this._audioBuffer;
  57496. this._soundSource.connect(this._inputAudioNode);
  57497. this._soundSource.loop = this.loop;
  57498. this._soundSource.playbackRate.value = this._playbackRate;
  57499. this._soundSource.onended = function () { _this._onended(); };
  57500. if (this._soundSource.buffer) {
  57501. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57502. }
  57503. }
  57504. this._startTime = startTime;
  57505. this.isPlaying = true;
  57506. this.isPaused = false;
  57507. }
  57508. catch (ex) {
  57509. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57510. }
  57511. }
  57512. };
  57513. Sound.prototype._onended = function () {
  57514. this.isPlaying = false;
  57515. if (this.onended) {
  57516. this.onended();
  57517. }
  57518. };
  57519. /**
  57520. * Stop the sound
  57521. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57522. */
  57523. Sound.prototype.stop = function (time) {
  57524. if (this.isPlaying) {
  57525. if (this._streaming) {
  57526. this._htmlAudioElement.pause();
  57527. // Test needed for Firefox or it will generate an Invalid State Error
  57528. if (this._htmlAudioElement.currentTime > 0) {
  57529. this._htmlAudioElement.currentTime = 0;
  57530. }
  57531. }
  57532. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57533. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57534. this._soundSource.stop(stopTime);
  57535. this._soundSource.onended = function () { };
  57536. if (!this.isPaused) {
  57537. this._startOffset = 0;
  57538. }
  57539. }
  57540. this.isPlaying = false;
  57541. }
  57542. };
  57543. Sound.prototype.pause = function () {
  57544. if (this.isPlaying) {
  57545. this.isPaused = true;
  57546. if (this._streaming) {
  57547. this._htmlAudioElement.pause();
  57548. }
  57549. else if (BABYLON.Engine.audioEngine.audioContext) {
  57550. this.stop(0);
  57551. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  57552. }
  57553. }
  57554. };
  57555. Sound.prototype.setVolume = function (newVolume, time) {
  57556. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  57557. if (time && BABYLON.Engine.audioEngine.audioContext) {
  57558. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  57559. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  57560. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  57561. }
  57562. else {
  57563. this._soundGain.gain.value = newVolume;
  57564. }
  57565. }
  57566. this._volume = newVolume;
  57567. };
  57568. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  57569. this._playbackRate = newPlaybackRate;
  57570. if (this.isPlaying) {
  57571. if (this._streaming) {
  57572. this._htmlAudioElement.playbackRate = this._playbackRate;
  57573. }
  57574. else if (this._soundSource) {
  57575. this._soundSource.playbackRate.value = this._playbackRate;
  57576. }
  57577. }
  57578. };
  57579. Sound.prototype.getVolume = function () {
  57580. return this._volume;
  57581. };
  57582. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  57583. var _this = this;
  57584. if (this._connectedMesh && this._registerFunc) {
  57585. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57586. this._registerFunc = null;
  57587. }
  57588. this._connectedMesh = meshToConnectTo;
  57589. if (!this.spatialSound) {
  57590. this.spatialSound = true;
  57591. this._createSpatialParameters();
  57592. if (this.isPlaying && this.loop) {
  57593. this.stop();
  57594. this.play();
  57595. }
  57596. }
  57597. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  57598. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  57599. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  57600. };
  57601. Sound.prototype.detachFromMesh = function () {
  57602. if (this._connectedMesh && this._registerFunc) {
  57603. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57604. this._registerFunc = null;
  57605. this._connectedMesh = null;
  57606. }
  57607. };
  57608. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  57609. if (!node.getBoundingInfo) {
  57610. return;
  57611. }
  57612. var mesh = node;
  57613. var boundingInfo = mesh.getBoundingInfo();
  57614. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  57615. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  57616. this._updateDirection();
  57617. }
  57618. };
  57619. Sound.prototype.clone = function () {
  57620. var _this = this;
  57621. if (!this._streaming) {
  57622. var setBufferAndRun = function () {
  57623. if (_this._isReadyToPlay) {
  57624. clonedSound._audioBuffer = _this.getAudioBuffer();
  57625. clonedSound._isReadyToPlay = true;
  57626. if (clonedSound.autoplay) {
  57627. clonedSound.play();
  57628. }
  57629. }
  57630. else {
  57631. window.setTimeout(setBufferAndRun, 300);
  57632. }
  57633. };
  57634. var currentOptions = {
  57635. autoplay: this.autoplay, loop: this.loop,
  57636. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  57637. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  57638. refDistance: this.refDistance, distanceModel: this.distanceModel
  57639. };
  57640. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  57641. if (this.useCustomAttenuation) {
  57642. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  57643. }
  57644. clonedSound.setPosition(this._position);
  57645. clonedSound.setPlaybackRate(this._playbackRate);
  57646. setBufferAndRun();
  57647. return clonedSound;
  57648. }
  57649. else {
  57650. return null;
  57651. }
  57652. };
  57653. Sound.prototype.getAudioBuffer = function () {
  57654. return this._audioBuffer;
  57655. };
  57656. Sound.prototype.serialize = function () {
  57657. var serializationObject = {
  57658. name: this.name,
  57659. url: this.name,
  57660. autoplay: this.autoplay,
  57661. loop: this.loop,
  57662. volume: this._volume,
  57663. spatialSound: this.spatialSound,
  57664. maxDistance: this.maxDistance,
  57665. rolloffFactor: this.rolloffFactor,
  57666. refDistance: this.refDistance,
  57667. distanceModel: this.distanceModel,
  57668. playbackRate: this._playbackRate,
  57669. panningModel: this._panningModel,
  57670. soundTrackId: this.soundTrackId
  57671. };
  57672. if (this.spatialSound) {
  57673. if (this._connectedMesh)
  57674. serializationObject.connectedMeshId = this._connectedMesh.id;
  57675. serializationObject.position = this._position.asArray();
  57676. serializationObject.refDistance = this.refDistance;
  57677. serializationObject.distanceModel = this.distanceModel;
  57678. serializationObject.isDirectional = this._isDirectional;
  57679. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57680. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57681. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57682. serializationObject.coneOuterGain = this._coneOuterGain;
  57683. }
  57684. return serializationObject;
  57685. };
  57686. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57687. var soundName = parsedSound.name;
  57688. var soundUrl;
  57689. if (parsedSound.url) {
  57690. soundUrl = rootUrl + parsedSound.url;
  57691. }
  57692. else {
  57693. soundUrl = rootUrl + soundName;
  57694. }
  57695. var options = {
  57696. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57697. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57698. rolloffFactor: parsedSound.rolloffFactor,
  57699. refDistance: parsedSound.refDistance,
  57700. distanceModel: parsedSound.distanceModel,
  57701. playbackRate: parsedSound.playbackRate
  57702. };
  57703. var newSound;
  57704. if (!sourceSound) {
  57705. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57706. scene._addPendingData(newSound);
  57707. }
  57708. else {
  57709. var setBufferAndRun = function () {
  57710. if (sourceSound._isReadyToPlay) {
  57711. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57712. newSound._isReadyToPlay = true;
  57713. if (newSound.autoplay) {
  57714. newSound.play();
  57715. }
  57716. }
  57717. else {
  57718. window.setTimeout(setBufferAndRun, 300);
  57719. }
  57720. };
  57721. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57722. setBufferAndRun();
  57723. }
  57724. if (parsedSound.position) {
  57725. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57726. newSound.setPosition(soundPosition);
  57727. }
  57728. if (parsedSound.isDirectional) {
  57729. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57730. if (parsedSound.localDirectionToMesh) {
  57731. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57732. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57733. }
  57734. }
  57735. if (parsedSound.connectedMeshId) {
  57736. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57737. if (connectedMesh) {
  57738. newSound.attachToMesh(connectedMesh);
  57739. }
  57740. }
  57741. return newSound;
  57742. };
  57743. return Sound;
  57744. }());
  57745. BABYLON.Sound = Sound;
  57746. })(BABYLON || (BABYLON = {}));
  57747. //# sourceMappingURL=babylon.sound.js.map
  57748. var BABYLON;
  57749. (function (BABYLON) {
  57750. var SoundTrack = /** @class */ (function () {
  57751. function SoundTrack(scene, options) {
  57752. this.id = -1;
  57753. this._isMainTrack = false;
  57754. this._isInitialized = false;
  57755. this._scene = scene;
  57756. this.soundCollection = new Array();
  57757. this._options = options;
  57758. if (!this._isMainTrack) {
  57759. this._scene.soundTracks.push(this);
  57760. this.id = this._scene.soundTracks.length - 1;
  57761. }
  57762. }
  57763. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57764. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57765. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57766. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57767. if (this._options) {
  57768. if (this._options.volume) {
  57769. this._outputAudioNode.gain.value = this._options.volume;
  57770. }
  57771. if (this._options.mainTrack) {
  57772. this._isMainTrack = this._options.mainTrack;
  57773. }
  57774. }
  57775. this._isInitialized = true;
  57776. }
  57777. };
  57778. SoundTrack.prototype.dispose = function () {
  57779. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57780. if (this._connectedAnalyser) {
  57781. this._connectedAnalyser.stopDebugCanvas();
  57782. }
  57783. while (this.soundCollection.length) {
  57784. this.soundCollection[0].dispose();
  57785. }
  57786. if (this._outputAudioNode) {
  57787. this._outputAudioNode.disconnect();
  57788. }
  57789. this._outputAudioNode = null;
  57790. }
  57791. };
  57792. SoundTrack.prototype.AddSound = function (sound) {
  57793. if (!this._isInitialized) {
  57794. this._initializeSoundTrackAudioGraph();
  57795. }
  57796. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57797. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57798. }
  57799. if (sound.soundTrackId) {
  57800. if (sound.soundTrackId === -1) {
  57801. this._scene.mainSoundTrack.RemoveSound(sound);
  57802. }
  57803. else {
  57804. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57805. }
  57806. }
  57807. this.soundCollection.push(sound);
  57808. sound.soundTrackId = this.id;
  57809. };
  57810. SoundTrack.prototype.RemoveSound = function (sound) {
  57811. var index = this.soundCollection.indexOf(sound);
  57812. if (index !== -1) {
  57813. this.soundCollection.splice(index, 1);
  57814. }
  57815. };
  57816. SoundTrack.prototype.setVolume = function (newVolume) {
  57817. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57818. this._outputAudioNode.gain.value = newVolume;
  57819. }
  57820. };
  57821. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57822. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57823. for (var i = 0; i < this.soundCollection.length; i++) {
  57824. this.soundCollection[i].switchPanningModelToHRTF();
  57825. }
  57826. }
  57827. };
  57828. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57829. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57830. for (var i = 0; i < this.soundCollection.length; i++) {
  57831. this.soundCollection[i].switchPanningModelToEqualPower();
  57832. }
  57833. }
  57834. };
  57835. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57836. if (this._connectedAnalyser) {
  57837. this._connectedAnalyser.stopDebugCanvas();
  57838. }
  57839. this._connectedAnalyser = analyser;
  57840. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57841. this._outputAudioNode.disconnect();
  57842. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57843. }
  57844. };
  57845. return SoundTrack;
  57846. }());
  57847. BABYLON.SoundTrack = SoundTrack;
  57848. })(BABYLON || (BABYLON = {}));
  57849. //# sourceMappingURL=babylon.soundtrack.js.map
  57850. var BABYLON;
  57851. (function (BABYLON) {
  57852. var Analyser = /** @class */ (function () {
  57853. function Analyser(scene) {
  57854. this.SMOOTHING = 0.75;
  57855. this.FFT_SIZE = 512;
  57856. this.BARGRAPHAMPLITUDE = 256;
  57857. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57858. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57859. this._scene = scene;
  57860. this._audioEngine = BABYLON.Engine.audioEngine;
  57861. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57862. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57863. this._webAudioAnalyser.minDecibels = -140;
  57864. this._webAudioAnalyser.maxDecibels = 0;
  57865. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57866. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57867. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57868. }
  57869. }
  57870. Analyser.prototype.getFrequencyBinCount = function () {
  57871. if (this._audioEngine.canUseWebAudio) {
  57872. return this._webAudioAnalyser.frequencyBinCount;
  57873. }
  57874. else {
  57875. return 0;
  57876. }
  57877. };
  57878. Analyser.prototype.getByteFrequencyData = function () {
  57879. if (this._audioEngine.canUseWebAudio) {
  57880. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57881. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57882. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57883. }
  57884. return this._byteFreqs;
  57885. };
  57886. Analyser.prototype.getByteTimeDomainData = function () {
  57887. if (this._audioEngine.canUseWebAudio) {
  57888. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57889. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57890. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57891. }
  57892. return this._byteTime;
  57893. };
  57894. Analyser.prototype.getFloatFrequencyData = function () {
  57895. if (this._audioEngine.canUseWebAudio) {
  57896. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57897. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57898. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57899. }
  57900. return this._floatFreqs;
  57901. };
  57902. Analyser.prototype.drawDebugCanvas = function () {
  57903. var _this = this;
  57904. if (this._audioEngine.canUseWebAudio) {
  57905. if (!this._debugCanvas) {
  57906. this._debugCanvas = document.createElement("canvas");
  57907. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57908. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57909. this._debugCanvas.style.position = "absolute";
  57910. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57911. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57912. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57913. document.body.appendChild(this._debugCanvas);
  57914. this._registerFunc = function () {
  57915. _this.drawDebugCanvas();
  57916. };
  57917. this._scene.registerBeforeRender(this._registerFunc);
  57918. }
  57919. if (this._registerFunc && this._debugCanvasContext) {
  57920. var workingArray = this.getByteFrequencyData();
  57921. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57922. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57923. // Draw the frequency domain chart.
  57924. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57925. var value = workingArray[i];
  57926. var percent = value / this.BARGRAPHAMPLITUDE;
  57927. var height = this.DEBUGCANVASSIZE.height * percent;
  57928. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57929. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57930. var hue = i / this.getFrequencyBinCount() * 360;
  57931. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57932. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57933. }
  57934. }
  57935. }
  57936. };
  57937. Analyser.prototype.stopDebugCanvas = function () {
  57938. if (this._debugCanvas) {
  57939. if (this._registerFunc) {
  57940. this._scene.unregisterBeforeRender(this._registerFunc);
  57941. this._registerFunc = null;
  57942. }
  57943. document.body.removeChild(this._debugCanvas);
  57944. this._debugCanvas = null;
  57945. this._debugCanvasContext = null;
  57946. }
  57947. };
  57948. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57949. if (this._audioEngine.canUseWebAudio) {
  57950. inputAudioNode.connect(this._webAudioAnalyser);
  57951. this._webAudioAnalyser.connect(outputAudioNode);
  57952. }
  57953. };
  57954. Analyser.prototype.dispose = function () {
  57955. if (this._audioEngine.canUseWebAudio) {
  57956. this._webAudioAnalyser.disconnect();
  57957. }
  57958. };
  57959. return Analyser;
  57960. }());
  57961. BABYLON.Analyser = Analyser;
  57962. })(BABYLON || (BABYLON = {}));
  57963. //# sourceMappingURL=babylon.analyser.js.map
  57964. var BABYLON;
  57965. (function (BABYLON) {
  57966. var CubeTexture = /** @class */ (function (_super) {
  57967. __extends(CubeTexture, _super);
  57968. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57969. if (extensions === void 0) { extensions = null; }
  57970. if (noMipmap === void 0) { noMipmap = false; }
  57971. if (files === void 0) { files = null; }
  57972. if (onLoad === void 0) { onLoad = null; }
  57973. if (onError === void 0) { onError = null; }
  57974. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57975. if (prefiltered === void 0) { prefiltered = false; }
  57976. if (forcedExtension === void 0) { forcedExtension = null; }
  57977. var _this = _super.call(this, scene) || this;
  57978. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57979. /**
  57980. * Gets or sets the center of the bounding box associated with the cube texture
  57981. * It must define where the camera used to render the texture was set
  57982. */
  57983. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57984. _this.name = rootUrl;
  57985. _this.url = rootUrl;
  57986. _this._noMipmap = noMipmap;
  57987. _this.hasAlpha = false;
  57988. _this._format = format;
  57989. _this._prefiltered = prefiltered;
  57990. _this.isCube = true;
  57991. _this._textureMatrix = BABYLON.Matrix.Identity();
  57992. if (prefiltered) {
  57993. _this.gammaSpace = false;
  57994. }
  57995. if (!rootUrl && !files) {
  57996. return _this;
  57997. }
  57998. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57999. var lastDot = rootUrl.lastIndexOf(".");
  58000. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58001. var isDDS = (extension === ".dds");
  58002. if (!files) {
  58003. if (!isDDS && !extensions) {
  58004. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58005. }
  58006. files = [];
  58007. if (extensions) {
  58008. for (var index = 0; index < extensions.length; index++) {
  58009. files.push(rootUrl + extensions[index]);
  58010. }
  58011. }
  58012. }
  58013. _this._files = files;
  58014. if (!_this._texture) {
  58015. if (!scene.useDelayedTextureLoading) {
  58016. if (prefiltered) {
  58017. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58018. }
  58019. else {
  58020. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58021. }
  58022. }
  58023. else {
  58024. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58025. }
  58026. }
  58027. else if (onLoad) {
  58028. if (_this._texture.isReady) {
  58029. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58030. }
  58031. else {
  58032. _this._texture.onLoadedObservable.add(onLoad);
  58033. }
  58034. }
  58035. return _this;
  58036. }
  58037. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58038. get: function () {
  58039. return this._boundingBoxSize;
  58040. },
  58041. /**
  58042. * Gets or sets the size of the bounding box associated with the cube texture
  58043. * When defined, the cubemap will switch to local mode
  58044. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58045. * @example https://www.babylonjs-playground.com/#RNASML
  58046. */
  58047. set: function (value) {
  58048. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58049. return;
  58050. }
  58051. this._boundingBoxSize = value;
  58052. var scene = this.getScene();
  58053. if (scene) {
  58054. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58055. }
  58056. },
  58057. enumerable: true,
  58058. configurable: true
  58059. });
  58060. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58061. var rootUrlKey = "";
  58062. files.forEach(function (url) { return rootUrlKey += url; });
  58063. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58064. };
  58065. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58066. if (forcedExtension === void 0) { forcedExtension = null; }
  58067. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58068. };
  58069. // Methods
  58070. CubeTexture.prototype.delayLoad = function () {
  58071. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58072. return;
  58073. }
  58074. var scene = this.getScene();
  58075. if (!scene) {
  58076. return;
  58077. }
  58078. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58079. this._texture = this._getFromCache(this.url, this._noMipmap);
  58080. if (!this._texture) {
  58081. if (this._prefiltered) {
  58082. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58083. }
  58084. else {
  58085. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58086. }
  58087. }
  58088. };
  58089. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58090. return this._textureMatrix;
  58091. };
  58092. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58093. this._textureMatrix = value;
  58094. };
  58095. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58096. var texture = BABYLON.SerializationHelper.Parse(function () {
  58097. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58098. }, parsedTexture, scene);
  58099. // Local Cubemaps
  58100. if (parsedTexture.boundingBoxPosition) {
  58101. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58102. }
  58103. if (parsedTexture.boundingBoxSize) {
  58104. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58105. }
  58106. // Animations
  58107. if (parsedTexture.animations) {
  58108. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58109. var parsedAnimation = parsedTexture.animations[animationIndex];
  58110. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58111. }
  58112. }
  58113. return texture;
  58114. };
  58115. CubeTexture.prototype.clone = function () {
  58116. var _this = this;
  58117. return BABYLON.SerializationHelper.Clone(function () {
  58118. var scene = _this.getScene();
  58119. if (!scene) {
  58120. return _this;
  58121. }
  58122. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58123. }, this);
  58124. };
  58125. return CubeTexture;
  58126. }(BABYLON.BaseTexture));
  58127. BABYLON.CubeTexture = CubeTexture;
  58128. })(BABYLON || (BABYLON = {}));
  58129. //# sourceMappingURL=babylon.cubeTexture.js.map
  58130. var BABYLON;
  58131. (function (BABYLON) {
  58132. var RenderTargetTexture = /** @class */ (function (_super) {
  58133. __extends(RenderTargetTexture, _super);
  58134. /**
  58135. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58136. * or used a shadow, depth texture...
  58137. * @param name The friendly name of the texture
  58138. * @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)
  58139. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58140. * @param generateMipMaps True if mip maps need to be generated after render.
  58141. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58142. * @param type The type of the buffer in the RTT (int, half float, float...)
  58143. * @param isCube True if a cube texture needs to be created
  58144. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58145. * @param generateDepthBuffer True to generate a depth buffer
  58146. * @param generateStencilBuffer True to generate a stencil buffer
  58147. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58148. */
  58149. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58150. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58151. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58152. if (isCube === void 0) { isCube = false; }
  58153. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58154. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58155. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58156. if (isMulti === void 0) { isMulti = false; }
  58157. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58158. _this.isCube = isCube;
  58159. /**
  58160. * Use this list to define the list of mesh you want to render.
  58161. */
  58162. _this.renderList = new Array();
  58163. _this.renderParticles = true;
  58164. _this.renderSprites = false;
  58165. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58166. _this.ignoreCameraViewport = false;
  58167. // Events
  58168. /**
  58169. * An event triggered when the texture is unbind.
  58170. * @type {BABYLON.Observable}
  58171. */
  58172. _this.onBeforeBindObservable = new BABYLON.Observable();
  58173. /**
  58174. * An event triggered when the texture is unbind.
  58175. * @type {BABYLON.Observable}
  58176. */
  58177. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58178. /**
  58179. * An event triggered before rendering the texture
  58180. * @type {BABYLON.Observable}
  58181. */
  58182. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58183. /**
  58184. * An event triggered after rendering the texture
  58185. * @type {BABYLON.Observable}
  58186. */
  58187. _this.onAfterRenderObservable = new BABYLON.Observable();
  58188. /**
  58189. * An event triggered after the texture clear
  58190. * @type {BABYLON.Observable}
  58191. */
  58192. _this.onClearObservable = new BABYLON.Observable();
  58193. _this._currentRefreshId = -1;
  58194. _this._refreshRate = 1;
  58195. _this._samples = 1;
  58196. /**
  58197. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58198. * It must define where the camera used to render the texture is set
  58199. */
  58200. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58201. scene = _this.getScene();
  58202. if (!scene) {
  58203. return _this;
  58204. }
  58205. _this._engine = scene.getEngine();
  58206. _this.name = name;
  58207. _this.isRenderTarget = true;
  58208. _this._initialSizeParameter = size;
  58209. _this._processSizeParameter(size);
  58210. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58211. });
  58212. _this._generateMipMaps = generateMipMaps ? true : false;
  58213. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58214. // Rendering groups
  58215. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58216. if (isMulti) {
  58217. return _this;
  58218. }
  58219. _this._renderTargetOptions = {
  58220. generateMipMaps: generateMipMaps,
  58221. type: type,
  58222. samplingMode: samplingMode,
  58223. generateDepthBuffer: generateDepthBuffer,
  58224. generateStencilBuffer: generateStencilBuffer
  58225. };
  58226. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58227. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58228. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58229. }
  58230. if (isCube) {
  58231. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58232. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58233. _this._textureMatrix = BABYLON.Matrix.Identity();
  58234. }
  58235. else {
  58236. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58237. }
  58238. return _this;
  58239. }
  58240. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58241. get: function () {
  58242. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58243. },
  58244. enumerable: true,
  58245. configurable: true
  58246. });
  58247. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58248. get: function () {
  58249. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58250. },
  58251. enumerable: true,
  58252. configurable: true
  58253. });
  58254. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58255. get: function () {
  58256. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58257. },
  58258. enumerable: true,
  58259. configurable: true
  58260. });
  58261. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58262. set: function (callback) {
  58263. if (this._onAfterUnbindObserver) {
  58264. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58265. }
  58266. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58267. },
  58268. enumerable: true,
  58269. configurable: true
  58270. });
  58271. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58272. set: function (callback) {
  58273. if (this._onBeforeRenderObserver) {
  58274. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58275. }
  58276. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58277. },
  58278. enumerable: true,
  58279. configurable: true
  58280. });
  58281. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58282. set: function (callback) {
  58283. if (this._onAfterRenderObserver) {
  58284. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58285. }
  58286. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58287. },
  58288. enumerable: true,
  58289. configurable: true
  58290. });
  58291. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58292. set: function (callback) {
  58293. if (this._onClearObserver) {
  58294. this.onClearObservable.remove(this._onClearObserver);
  58295. }
  58296. this._onClearObserver = this.onClearObservable.add(callback);
  58297. },
  58298. enumerable: true,
  58299. configurable: true
  58300. });
  58301. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58302. get: function () {
  58303. return this._renderTargetOptions;
  58304. },
  58305. enumerable: true,
  58306. configurable: true
  58307. });
  58308. RenderTargetTexture.prototype._onRatioRescale = function () {
  58309. if (this._sizeRatio) {
  58310. this.resize(this._initialSizeParameter);
  58311. }
  58312. };
  58313. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  58314. get: function () {
  58315. return this._boundingBoxSize;
  58316. },
  58317. /**
  58318. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  58319. * When defined, the cubemap will switch to local mode
  58320. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58321. * @example https://www.babylonjs-playground.com/#RNASML
  58322. */
  58323. set: function (value) {
  58324. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58325. return;
  58326. }
  58327. this._boundingBoxSize = value;
  58328. var scene = this.getScene();
  58329. if (scene) {
  58330. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58331. }
  58332. },
  58333. enumerable: true,
  58334. configurable: true
  58335. });
  58336. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  58337. if (size.ratio) {
  58338. this._sizeRatio = size.ratio;
  58339. this._size = {
  58340. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  58341. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  58342. };
  58343. }
  58344. else {
  58345. this._size = size;
  58346. }
  58347. };
  58348. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  58349. get: function () {
  58350. return this._samples;
  58351. },
  58352. set: function (value) {
  58353. if (this._samples === value) {
  58354. return;
  58355. }
  58356. var scene = this.getScene();
  58357. if (!scene) {
  58358. return;
  58359. }
  58360. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58361. },
  58362. enumerable: true,
  58363. configurable: true
  58364. });
  58365. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58366. this._currentRefreshId = -1;
  58367. };
  58368. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58369. get: function () {
  58370. return this._refreshRate;
  58371. },
  58372. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58373. set: function (value) {
  58374. this._refreshRate = value;
  58375. this.resetRefreshCounter();
  58376. },
  58377. enumerable: true,
  58378. configurable: true
  58379. });
  58380. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58381. if (!this._postProcessManager) {
  58382. var scene = this.getScene();
  58383. if (!scene) {
  58384. return;
  58385. }
  58386. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58387. this._postProcesses = new Array();
  58388. }
  58389. this._postProcesses.push(postProcess);
  58390. this._postProcesses[0].autoClear = false;
  58391. };
  58392. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58393. if (!this._postProcesses) {
  58394. return;
  58395. }
  58396. if (dispose) {
  58397. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58398. var postProcess = _a[_i];
  58399. postProcess.dispose();
  58400. }
  58401. }
  58402. this._postProcesses = [];
  58403. };
  58404. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58405. if (!this._postProcesses) {
  58406. return;
  58407. }
  58408. var index = this._postProcesses.indexOf(postProcess);
  58409. if (index === -1) {
  58410. return;
  58411. }
  58412. this._postProcesses.splice(index, 1);
  58413. if (this._postProcesses.length > 0) {
  58414. this._postProcesses[0].autoClear = false;
  58415. }
  58416. };
  58417. RenderTargetTexture.prototype._shouldRender = function () {
  58418. if (this._currentRefreshId === -1) {
  58419. this._currentRefreshId = 1;
  58420. return true;
  58421. }
  58422. if (this.refreshRate === this._currentRefreshId) {
  58423. this._currentRefreshId = 1;
  58424. return true;
  58425. }
  58426. this._currentRefreshId++;
  58427. return false;
  58428. };
  58429. RenderTargetTexture.prototype.getRenderSize = function () {
  58430. if (this._size.width) {
  58431. return this._size.width;
  58432. }
  58433. return this._size;
  58434. };
  58435. RenderTargetTexture.prototype.getRenderWidth = function () {
  58436. if (this._size.width) {
  58437. return this._size.width;
  58438. }
  58439. return this._size;
  58440. };
  58441. RenderTargetTexture.prototype.getRenderHeight = function () {
  58442. if (this._size.width) {
  58443. return this._size.height;
  58444. }
  58445. return this._size;
  58446. };
  58447. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58448. get: function () {
  58449. return true;
  58450. },
  58451. enumerable: true,
  58452. configurable: true
  58453. });
  58454. RenderTargetTexture.prototype.scale = function (ratio) {
  58455. var newSize = this.getRenderSize() * ratio;
  58456. this.resize(newSize);
  58457. };
  58458. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58459. if (this.isCube) {
  58460. return this._textureMatrix;
  58461. }
  58462. return _super.prototype.getReflectionTextureMatrix.call(this);
  58463. };
  58464. RenderTargetTexture.prototype.resize = function (size) {
  58465. this.releaseInternalTexture();
  58466. var scene = this.getScene();
  58467. if (!scene) {
  58468. return;
  58469. }
  58470. this._processSizeParameter(size);
  58471. if (this.isCube) {
  58472. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58473. }
  58474. else {
  58475. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58476. }
  58477. };
  58478. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58479. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58480. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58481. var scene = this.getScene();
  58482. if (!scene) {
  58483. return;
  58484. }
  58485. var engine = scene.getEngine();
  58486. if (this.useCameraPostProcesses !== undefined) {
  58487. useCameraPostProcess = this.useCameraPostProcesses;
  58488. }
  58489. if (this._waitingRenderList) {
  58490. this.renderList = [];
  58491. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58492. var id = this._waitingRenderList[index];
  58493. var mesh_1 = scene.getMeshByID(id);
  58494. if (mesh_1) {
  58495. this.renderList.push(mesh_1);
  58496. }
  58497. }
  58498. delete this._waitingRenderList;
  58499. }
  58500. // Is predicate defined?
  58501. if (this.renderListPredicate) {
  58502. if (this.renderList) {
  58503. this.renderList.splice(0); // Clear previous renderList
  58504. }
  58505. else {
  58506. this.renderList = [];
  58507. }
  58508. var scene = this.getScene();
  58509. if (!scene) {
  58510. return;
  58511. }
  58512. var sceneMeshes = scene.meshes;
  58513. for (var index = 0; index < sceneMeshes.length; index++) {
  58514. var mesh = sceneMeshes[index];
  58515. if (this.renderListPredicate(mesh)) {
  58516. this.renderList.push(mesh);
  58517. }
  58518. }
  58519. }
  58520. this.onBeforeBindObservable.notifyObservers(this);
  58521. // Set custom projection.
  58522. // Needs to be before binding to prevent changing the aspect ratio.
  58523. var camera;
  58524. if (this.activeCamera) {
  58525. camera = this.activeCamera;
  58526. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58527. if (this.activeCamera !== scene.activeCamera) {
  58528. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  58529. }
  58530. }
  58531. else {
  58532. camera = scene.activeCamera;
  58533. if (camera) {
  58534. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58535. }
  58536. }
  58537. // Prepare renderingManager
  58538. this._renderingManager.reset();
  58539. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  58540. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  58541. var sceneRenderId = scene.getRenderId();
  58542. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  58543. var mesh = currentRenderList[meshIndex];
  58544. if (mesh) {
  58545. if (!mesh.isReady()) {
  58546. // Reset _currentRefreshId
  58547. this.resetRefreshCounter();
  58548. continue;
  58549. }
  58550. mesh._preActivateForIntermediateRendering(sceneRenderId);
  58551. var isMasked = void 0;
  58552. if (!this.renderList && camera) {
  58553. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  58554. }
  58555. else {
  58556. isMasked = false;
  58557. }
  58558. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  58559. mesh._activate(sceneRenderId);
  58560. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  58561. var subMesh = mesh.subMeshes[subIndex];
  58562. scene._activeIndices.addCount(subMesh.indexCount, false);
  58563. this._renderingManager.dispatch(subMesh, mesh);
  58564. }
  58565. }
  58566. }
  58567. }
  58568. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  58569. var particleSystem = scene.particleSystems[particleIndex];
  58570. var emitter = particleSystem.emitter;
  58571. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  58572. continue;
  58573. }
  58574. if (currentRenderList.indexOf(emitter) >= 0) {
  58575. this._renderingManager.dispatchParticles(particleSystem);
  58576. }
  58577. }
  58578. if (this.isCube) {
  58579. for (var face = 0; face < 6; face++) {
  58580. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58581. scene.incrementRenderId();
  58582. scene.resetCachedMaterial();
  58583. }
  58584. }
  58585. else {
  58586. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58587. }
  58588. this.onAfterUnbindObservable.notifyObservers(this);
  58589. if (scene.activeCamera) {
  58590. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  58591. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  58592. }
  58593. engine.setViewport(scene.activeCamera.viewport);
  58594. }
  58595. scene.resetCachedMaterial();
  58596. };
  58597. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  58598. var minimum = 128;
  58599. var x = renderDimension * scale;
  58600. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  58601. // Ensure we don't exceed the render dimension (while staying POT)
  58602. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  58603. };
  58604. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58605. var _this = this;
  58606. if (!this._texture) {
  58607. return;
  58608. }
  58609. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  58610. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58611. });
  58612. };
  58613. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  58614. var scene = this.getScene();
  58615. if (!scene) {
  58616. return;
  58617. }
  58618. var engine = scene.getEngine();
  58619. if (!this._texture) {
  58620. return;
  58621. }
  58622. // Bind
  58623. if (this._postProcessManager) {
  58624. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  58625. }
  58626. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  58627. if (this._texture) {
  58628. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  58629. }
  58630. }
  58631. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  58632. // Clear
  58633. if (this.onClearObservable.hasObservers()) {
  58634. this.onClearObservable.notifyObservers(engine);
  58635. }
  58636. else {
  58637. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  58638. }
  58639. if (!this._doNotChangeAspectRatio) {
  58640. scene.updateTransformMatrix(true);
  58641. }
  58642. // Render
  58643. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  58644. if (this._postProcessManager) {
  58645. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  58646. }
  58647. else if (useCameraPostProcess) {
  58648. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  58649. }
  58650. if (!this._doNotChangeAspectRatio) {
  58651. scene.updateTransformMatrix(true);
  58652. }
  58653. // Dump ?
  58654. if (dumpForDebug) {
  58655. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  58656. }
  58657. // Unbind
  58658. if (!this.isCube || faceIndex === 5) {
  58659. if (this.isCube) {
  58660. if (faceIndex === 5) {
  58661. engine.generateMipMapsForCubemap(this._texture);
  58662. }
  58663. }
  58664. this.unbindFrameBuffer(engine, faceIndex);
  58665. }
  58666. else {
  58667. this.onAfterRenderObservable.notifyObservers(faceIndex);
  58668. }
  58669. };
  58670. /**
  58671. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  58672. * This allowed control for front to back rendering or reversly depending of the special needs.
  58673. *
  58674. * @param renderingGroupId The rendering group id corresponding to its index
  58675. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  58676. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  58677. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  58678. */
  58679. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58680. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58681. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58682. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58683. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58684. };
  58685. /**
  58686. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58687. *
  58688. * @param renderingGroupId The rendering group id corresponding to its index
  58689. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58690. */
  58691. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58692. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58693. };
  58694. RenderTargetTexture.prototype.clone = function () {
  58695. var textureSize = this.getSize();
  58696. 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);
  58697. // Base texture
  58698. newTexture.hasAlpha = this.hasAlpha;
  58699. newTexture.level = this.level;
  58700. // RenderTarget Texture
  58701. newTexture.coordinatesMode = this.coordinatesMode;
  58702. if (this.renderList) {
  58703. newTexture.renderList = this.renderList.slice(0);
  58704. }
  58705. return newTexture;
  58706. };
  58707. RenderTargetTexture.prototype.serialize = function () {
  58708. if (!this.name) {
  58709. return null;
  58710. }
  58711. var serializationObject = _super.prototype.serialize.call(this);
  58712. serializationObject.renderTargetSize = this.getRenderSize();
  58713. serializationObject.renderList = [];
  58714. if (this.renderList) {
  58715. for (var index = 0; index < this.renderList.length; index++) {
  58716. serializationObject.renderList.push(this.renderList[index].id);
  58717. }
  58718. }
  58719. return serializationObject;
  58720. };
  58721. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58722. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58723. var objBuffer = this.getInternalTexture();
  58724. var scene = this.getScene();
  58725. if (objBuffer && scene) {
  58726. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58727. }
  58728. };
  58729. RenderTargetTexture.prototype.dispose = function () {
  58730. if (this._postProcessManager) {
  58731. this._postProcessManager.dispose();
  58732. this._postProcessManager = null;
  58733. }
  58734. this.clearPostProcesses(true);
  58735. if (this._resizeObserver) {
  58736. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58737. this._resizeObserver = null;
  58738. }
  58739. this.renderList = null;
  58740. // Remove from custom render targets
  58741. var scene = this.getScene();
  58742. if (!scene) {
  58743. return;
  58744. }
  58745. var index = scene.customRenderTargets.indexOf(this);
  58746. if (index >= 0) {
  58747. scene.customRenderTargets.splice(index, 1);
  58748. }
  58749. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58750. var camera = _a[_i];
  58751. index = camera.customRenderTargets.indexOf(this);
  58752. if (index >= 0) {
  58753. camera.customRenderTargets.splice(index, 1);
  58754. }
  58755. }
  58756. _super.prototype.dispose.call(this);
  58757. };
  58758. RenderTargetTexture.prototype._rebuild = function () {
  58759. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58760. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58761. }
  58762. if (this._postProcessManager) {
  58763. this._postProcessManager._rebuild();
  58764. }
  58765. };
  58766. /**
  58767. * Clear the info related to rendering groups preventing retention point in material dispose.
  58768. */
  58769. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  58770. if (this._renderingManager) {
  58771. this._renderingManager.freeRenderingGroups();
  58772. }
  58773. };
  58774. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58775. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58776. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58777. return RenderTargetTexture;
  58778. }(BABYLON.Texture));
  58779. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58780. })(BABYLON || (BABYLON = {}));
  58781. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58782. var BABYLON;
  58783. (function (BABYLON) {
  58784. ;
  58785. var MultiRenderTarget = /** @class */ (function (_super) {
  58786. __extends(MultiRenderTarget, _super);
  58787. function MultiRenderTarget(name, size, count, scene, options) {
  58788. var _this = this;
  58789. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58790. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58791. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58792. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58793. _this._engine = scene.getEngine();
  58794. if (!_this.isSupported) {
  58795. _this.dispose();
  58796. return;
  58797. }
  58798. var types = [];
  58799. var samplingModes = [];
  58800. for (var i = 0; i < count; i++) {
  58801. if (options && options.types && options.types[i] !== undefined) {
  58802. types.push(options.types[i]);
  58803. }
  58804. else {
  58805. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58806. }
  58807. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58808. samplingModes.push(options.samplingModes[i]);
  58809. }
  58810. else {
  58811. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58812. }
  58813. }
  58814. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58815. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58816. _this._size = size;
  58817. _this._multiRenderTargetOptions = {
  58818. samplingModes: samplingModes,
  58819. generateMipMaps: generateMipMaps,
  58820. generateDepthBuffer: generateDepthBuffer,
  58821. generateStencilBuffer: generateStencilBuffer,
  58822. generateDepthTexture: generateDepthTexture,
  58823. types: types,
  58824. textureCount: count
  58825. };
  58826. _this._createInternalTextures();
  58827. _this._createTextures();
  58828. return _this;
  58829. }
  58830. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58831. get: function () {
  58832. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58833. },
  58834. enumerable: true,
  58835. configurable: true
  58836. });
  58837. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58838. get: function () {
  58839. return this._textures;
  58840. },
  58841. enumerable: true,
  58842. configurable: true
  58843. });
  58844. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58845. get: function () {
  58846. return this._textures[this._textures.length - 1];
  58847. },
  58848. enumerable: true,
  58849. configurable: true
  58850. });
  58851. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58852. set: function (wrap) {
  58853. if (this._textures) {
  58854. for (var i = 0; i < this._textures.length; i++) {
  58855. this._textures[i].wrapU = wrap;
  58856. }
  58857. }
  58858. },
  58859. enumerable: true,
  58860. configurable: true
  58861. });
  58862. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58863. set: function (wrap) {
  58864. if (this._textures) {
  58865. for (var i = 0; i < this._textures.length; i++) {
  58866. this._textures[i].wrapV = wrap;
  58867. }
  58868. }
  58869. },
  58870. enumerable: true,
  58871. configurable: true
  58872. });
  58873. MultiRenderTarget.prototype._rebuild = function () {
  58874. this.releaseInternalTextures();
  58875. this._createInternalTextures();
  58876. for (var i = 0; i < this._internalTextures.length; i++) {
  58877. var texture = this._textures[i];
  58878. texture._texture = this._internalTextures[i];
  58879. }
  58880. // Keeps references to frame buffer and stencil/depth buffer
  58881. this._texture = this._internalTextures[0];
  58882. };
  58883. MultiRenderTarget.prototype._createInternalTextures = function () {
  58884. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58885. };
  58886. MultiRenderTarget.prototype._createTextures = function () {
  58887. this._textures = [];
  58888. for (var i = 0; i < this._internalTextures.length; i++) {
  58889. var texture = new BABYLON.Texture(null, this.getScene());
  58890. texture._texture = this._internalTextures[i];
  58891. this._textures.push(texture);
  58892. }
  58893. // Keeps references to frame buffer and stencil/depth buffer
  58894. this._texture = this._internalTextures[0];
  58895. };
  58896. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58897. get: function () {
  58898. return this._samples;
  58899. },
  58900. set: function (value) {
  58901. if (this._samples === value) {
  58902. return;
  58903. }
  58904. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58905. },
  58906. enumerable: true,
  58907. configurable: true
  58908. });
  58909. MultiRenderTarget.prototype.resize = function (size) {
  58910. this.releaseInternalTextures();
  58911. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58912. this._createInternalTextures();
  58913. };
  58914. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58915. var _this = this;
  58916. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58917. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58918. });
  58919. };
  58920. MultiRenderTarget.prototype.dispose = function () {
  58921. this.releaseInternalTextures();
  58922. _super.prototype.dispose.call(this);
  58923. };
  58924. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58925. if (!this._internalTextures) {
  58926. return;
  58927. }
  58928. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58929. if (this._internalTextures[i] !== undefined) {
  58930. this._internalTextures[i].dispose();
  58931. this._internalTextures.splice(i, 1);
  58932. }
  58933. }
  58934. };
  58935. return MultiRenderTarget;
  58936. }(BABYLON.RenderTargetTexture));
  58937. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58938. })(BABYLON || (BABYLON = {}));
  58939. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58940. var BABYLON;
  58941. (function (BABYLON) {
  58942. var MirrorTexture = /** @class */ (function (_super) {
  58943. __extends(MirrorTexture, _super);
  58944. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58945. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58946. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58947. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58948. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58949. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58950. _this._transformMatrix = BABYLON.Matrix.Zero();
  58951. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58952. _this._adaptiveBlurKernel = 0;
  58953. _this._blurKernelX = 0;
  58954. _this._blurKernelY = 0;
  58955. _this._blurRatio = 1.0;
  58956. _this.ignoreCameraViewport = true;
  58957. _this.onBeforeRenderObservable.add(function () {
  58958. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58959. _this._savedViewMatrix = scene.getViewMatrix();
  58960. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58961. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58962. scene.clipPlane = _this.mirrorPlane;
  58963. scene.getEngine().cullBackFaces = false;
  58964. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58965. });
  58966. _this.onAfterRenderObservable.add(function () {
  58967. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58968. scene.getEngine().cullBackFaces = true;
  58969. scene._mirroredCameraPosition = null;
  58970. delete scene.clipPlane;
  58971. });
  58972. return _this;
  58973. }
  58974. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58975. get: function () {
  58976. return this._blurRatio;
  58977. },
  58978. set: function (value) {
  58979. if (this._blurRatio === value) {
  58980. return;
  58981. }
  58982. this._blurRatio = value;
  58983. this._preparePostProcesses();
  58984. },
  58985. enumerable: true,
  58986. configurable: true
  58987. });
  58988. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58989. set: function (value) {
  58990. this._adaptiveBlurKernel = value;
  58991. this._autoComputeBlurKernel();
  58992. },
  58993. enumerable: true,
  58994. configurable: true
  58995. });
  58996. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58997. set: function (value) {
  58998. this.blurKernelX = value;
  58999. this.blurKernelY = value;
  59000. },
  59001. enumerable: true,
  59002. configurable: true
  59003. });
  59004. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59005. get: function () {
  59006. return this._blurKernelX;
  59007. },
  59008. set: function (value) {
  59009. if (this._blurKernelX === value) {
  59010. return;
  59011. }
  59012. this._blurKernelX = value;
  59013. this._preparePostProcesses();
  59014. },
  59015. enumerable: true,
  59016. configurable: true
  59017. });
  59018. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59019. get: function () {
  59020. return this._blurKernelY;
  59021. },
  59022. set: function (value) {
  59023. if (this._blurKernelY === value) {
  59024. return;
  59025. }
  59026. this._blurKernelY = value;
  59027. this._preparePostProcesses();
  59028. },
  59029. enumerable: true,
  59030. configurable: true
  59031. });
  59032. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59033. var engine = this.getScene().getEngine();
  59034. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59035. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59036. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59037. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59038. };
  59039. MirrorTexture.prototype._onRatioRescale = function () {
  59040. if (this._sizeRatio) {
  59041. this.resize(this._initialSizeParameter);
  59042. if (!this._adaptiveBlurKernel) {
  59043. this._preparePostProcesses();
  59044. }
  59045. }
  59046. if (this._adaptiveBlurKernel) {
  59047. this._autoComputeBlurKernel();
  59048. }
  59049. };
  59050. MirrorTexture.prototype._preparePostProcesses = function () {
  59051. this.clearPostProcesses(true);
  59052. if (this._blurKernelX && this._blurKernelY) {
  59053. var engine = this.getScene().getEngine();
  59054. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59055. 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);
  59056. this._blurX.autoClear = false;
  59057. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59058. this._blurX.inputTexture = this._texture;
  59059. }
  59060. else {
  59061. this._blurX.alwaysForcePOT = true;
  59062. }
  59063. 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);
  59064. this._blurY.autoClear = false;
  59065. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59066. this.addPostProcess(this._blurX);
  59067. this.addPostProcess(this._blurY);
  59068. }
  59069. else {
  59070. if (this._blurY) {
  59071. this.removePostProcess(this._blurY);
  59072. this._blurY.dispose();
  59073. this._blurY = null;
  59074. }
  59075. if (this._blurX) {
  59076. this.removePostProcess(this._blurX);
  59077. this._blurX.dispose();
  59078. this._blurX = null;
  59079. }
  59080. }
  59081. };
  59082. MirrorTexture.prototype.clone = function () {
  59083. var scene = this.getScene();
  59084. if (!scene) {
  59085. return this;
  59086. }
  59087. var textureSize = this.getSize();
  59088. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59089. // Base texture
  59090. newTexture.hasAlpha = this.hasAlpha;
  59091. newTexture.level = this.level;
  59092. // Mirror Texture
  59093. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59094. if (this.renderList) {
  59095. newTexture.renderList = this.renderList.slice(0);
  59096. }
  59097. return newTexture;
  59098. };
  59099. MirrorTexture.prototype.serialize = function () {
  59100. if (!this.name) {
  59101. return null;
  59102. }
  59103. var serializationObject = _super.prototype.serialize.call(this);
  59104. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59105. return serializationObject;
  59106. };
  59107. return MirrorTexture;
  59108. }(BABYLON.RenderTargetTexture));
  59109. BABYLON.MirrorTexture = MirrorTexture;
  59110. })(BABYLON || (BABYLON = {}));
  59111. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59112. var BABYLON;
  59113. (function (BABYLON) {
  59114. /**
  59115. * Creates a refraction texture used by refraction channel of the standard material.
  59116. * @param name the texture name
  59117. * @param size size of the underlying texture
  59118. * @param scene root scene
  59119. */
  59120. var RefractionTexture = /** @class */ (function (_super) {
  59121. __extends(RefractionTexture, _super);
  59122. function RefractionTexture(name, size, scene, generateMipMaps) {
  59123. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59124. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59125. _this.depth = 2.0;
  59126. _this.onBeforeRenderObservable.add(function () {
  59127. scene.clipPlane = _this.refractionPlane;
  59128. });
  59129. _this.onAfterRenderObservable.add(function () {
  59130. delete scene.clipPlane;
  59131. });
  59132. return _this;
  59133. }
  59134. RefractionTexture.prototype.clone = function () {
  59135. var scene = this.getScene();
  59136. if (!scene) {
  59137. return this;
  59138. }
  59139. var textureSize = this.getSize();
  59140. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59141. // Base texture
  59142. newTexture.hasAlpha = this.hasAlpha;
  59143. newTexture.level = this.level;
  59144. // Refraction Texture
  59145. newTexture.refractionPlane = this.refractionPlane.clone();
  59146. if (this.renderList) {
  59147. newTexture.renderList = this.renderList.slice(0);
  59148. }
  59149. newTexture.depth = this.depth;
  59150. return newTexture;
  59151. };
  59152. RefractionTexture.prototype.serialize = function () {
  59153. if (!this.name) {
  59154. return null;
  59155. }
  59156. var serializationObject = _super.prototype.serialize.call(this);
  59157. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59158. serializationObject.depth = this.depth;
  59159. return serializationObject;
  59160. };
  59161. return RefractionTexture;
  59162. }(BABYLON.RenderTargetTexture));
  59163. BABYLON.RefractionTexture = RefractionTexture;
  59164. })(BABYLON || (BABYLON = {}));
  59165. //# sourceMappingURL=babylon.refractionTexture.js.map
  59166. var BABYLON;
  59167. (function (BABYLON) {
  59168. var DynamicTexture = /** @class */ (function (_super) {
  59169. __extends(DynamicTexture, _super);
  59170. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59171. if (scene === void 0) { scene = null; }
  59172. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59173. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59174. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59175. _this.name = name;
  59176. _this._engine = _this.getScene().getEngine();
  59177. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59178. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59179. _this._generateMipMaps = generateMipMaps;
  59180. if (options.getContext) {
  59181. _this._canvas = options;
  59182. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59183. }
  59184. else {
  59185. _this._canvas = document.createElement("canvas");
  59186. if (options.width) {
  59187. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59188. }
  59189. else {
  59190. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59191. }
  59192. }
  59193. var textureSize = _this.getSize();
  59194. _this._canvas.width = textureSize.width;
  59195. _this._canvas.height = textureSize.height;
  59196. _this._context = _this._canvas.getContext("2d");
  59197. return _this;
  59198. }
  59199. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59200. get: function () {
  59201. return true;
  59202. },
  59203. enumerable: true,
  59204. configurable: true
  59205. });
  59206. DynamicTexture.prototype._recreate = function (textureSize) {
  59207. this._canvas.width = textureSize.width;
  59208. this._canvas.height = textureSize.height;
  59209. this.releaseInternalTexture();
  59210. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59211. };
  59212. DynamicTexture.prototype.scale = function (ratio) {
  59213. var textureSize = this.getSize();
  59214. textureSize.width *= ratio;
  59215. textureSize.height *= ratio;
  59216. this._recreate(textureSize);
  59217. };
  59218. DynamicTexture.prototype.scaleTo = function (width, height) {
  59219. var textureSize = this.getSize();
  59220. textureSize.width = width;
  59221. textureSize.height = height;
  59222. this._recreate(textureSize);
  59223. };
  59224. DynamicTexture.prototype.getContext = function () {
  59225. return this._context;
  59226. };
  59227. DynamicTexture.prototype.clear = function () {
  59228. var size = this.getSize();
  59229. this._context.fillRect(0, 0, size.width, size.height);
  59230. };
  59231. DynamicTexture.prototype.update = function (invertY) {
  59232. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59233. };
  59234. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59235. if (update === void 0) { update = true; }
  59236. var size = this.getSize();
  59237. if (clearColor) {
  59238. this._context.fillStyle = clearColor;
  59239. this._context.fillRect(0, 0, size.width, size.height);
  59240. }
  59241. this._context.font = font;
  59242. if (x === null || x === undefined) {
  59243. var textSize = this._context.measureText(text);
  59244. x = (size.width - textSize.width) / 2;
  59245. }
  59246. if (y === null || y === undefined) {
  59247. var fontSize = parseInt((font.replace(/\D/g, '')));
  59248. ;
  59249. y = (size.height / 2) + (fontSize / 3.65);
  59250. }
  59251. this._context.fillStyle = color;
  59252. this._context.fillText(text, x, y);
  59253. if (update) {
  59254. this.update(invertY);
  59255. }
  59256. };
  59257. DynamicTexture.prototype.clone = function () {
  59258. var scene = this.getScene();
  59259. if (!scene) {
  59260. return this;
  59261. }
  59262. var textureSize = this.getSize();
  59263. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59264. // Base texture
  59265. newTexture.hasAlpha = this.hasAlpha;
  59266. newTexture.level = this.level;
  59267. // Dynamic Texture
  59268. newTexture.wrapU = this.wrapU;
  59269. newTexture.wrapV = this.wrapV;
  59270. return newTexture;
  59271. };
  59272. DynamicTexture.prototype._rebuild = function () {
  59273. this.update();
  59274. };
  59275. return DynamicTexture;
  59276. }(BABYLON.Texture));
  59277. BABYLON.DynamicTexture = DynamicTexture;
  59278. })(BABYLON || (BABYLON = {}));
  59279. //# sourceMappingURL=babylon.dynamicTexture.js.map
  59280. var BABYLON;
  59281. (function (BABYLON) {
  59282. var VideoTexture = /** @class */ (function (_super) {
  59283. __extends(VideoTexture, _super);
  59284. /**
  59285. * Creates a video texture.
  59286. * Sample : https://doc.babylonjs.com/how_to/video_texture
  59287. * @param {string | null} name optional name, will detect from video source, if not defined
  59288. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  59289. * @param {BABYLON.Scene} scene is obviously the current scene.
  59290. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  59291. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  59292. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  59293. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  59294. */
  59295. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  59296. if (generateMipMaps === void 0) { generateMipMaps = false; }
  59297. if (invertY === void 0) { invertY = false; }
  59298. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59299. if (settings === void 0) { settings = {
  59300. autoPlay: true,
  59301. loop: true,
  59302. autoUpdateTexture: true,
  59303. }; }
  59304. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59305. _this._createInternalTexture = function () {
  59306. if (_this._texture != null) {
  59307. return;
  59308. }
  59309. if (!_this._engine.needPOTTextures ||
  59310. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  59311. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59312. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59313. }
  59314. else {
  59315. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59316. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59317. _this._generateMipMaps = false;
  59318. }
  59319. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  59320. _this._texture.isReady = true;
  59321. _this._updateInternalTexture();
  59322. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  59323. _this.onLoadObservable.notifyObservers(_this);
  59324. }
  59325. };
  59326. _this.reset = function () {
  59327. if (_this._texture == null) {
  59328. return;
  59329. }
  59330. _this._texture.dispose();
  59331. _this._texture = null;
  59332. };
  59333. _this._updateInternalTexture = function (e) {
  59334. if (_this._texture == null || !_this._texture.isReady) {
  59335. return;
  59336. }
  59337. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  59338. return;
  59339. }
  59340. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  59341. };
  59342. _this._engine = _this.getScene().getEngine();
  59343. _this._generateMipMaps = generateMipMaps;
  59344. _this._samplingMode = samplingMode;
  59345. _this.autoUpdateTexture = settings.autoUpdateTexture;
  59346. _this.name = name || _this._getName(src);
  59347. _this.video = _this._getVideo(src);
  59348. if (settings.autoPlay !== undefined) {
  59349. _this.video.autoplay = settings.autoPlay;
  59350. }
  59351. if (settings.loop !== undefined) {
  59352. _this.video.loop = settings.loop;
  59353. }
  59354. _this.video.addEventListener("canplay", _this._createInternalTexture);
  59355. _this.video.addEventListener("paused", _this._updateInternalTexture);
  59356. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  59357. _this.video.addEventListener("emptied", _this.reset);
  59358. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  59359. _this._createInternalTexture();
  59360. }
  59361. return _this;
  59362. }
  59363. VideoTexture.prototype._getName = function (src) {
  59364. if (src instanceof HTMLVideoElement) {
  59365. return src.currentSrc;
  59366. }
  59367. if (typeof src === "object") {
  59368. return src.toString();
  59369. }
  59370. return src;
  59371. };
  59372. ;
  59373. VideoTexture.prototype._getVideo = function (src) {
  59374. if (src instanceof HTMLVideoElement) {
  59375. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59376. return src;
  59377. }
  59378. var video = document.createElement("video");
  59379. if (typeof src === "string") {
  59380. BABYLON.Tools.SetCorsBehavior(src, video);
  59381. video.src = src;
  59382. }
  59383. else {
  59384. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59385. src.forEach(function (url) {
  59386. var source = document.createElement("source");
  59387. source.src = url;
  59388. video.appendChild(source);
  59389. });
  59390. }
  59391. return video;
  59392. };
  59393. ;
  59394. /**
  59395. * Internal method to initiate `update`.
  59396. */
  59397. VideoTexture.prototype._rebuild = function () {
  59398. this.update();
  59399. };
  59400. /**
  59401. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59402. */
  59403. VideoTexture.prototype.update = function () {
  59404. if (!this.autoUpdateTexture) {
  59405. // Expecting user to call `updateTexture` manually
  59406. return;
  59407. }
  59408. this.updateTexture(true);
  59409. };
  59410. /**
  59411. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59412. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59413. */
  59414. VideoTexture.prototype.updateTexture = function (isVisible) {
  59415. if (!isVisible) {
  59416. return;
  59417. }
  59418. if (this.video.paused) {
  59419. return;
  59420. }
  59421. this._updateInternalTexture();
  59422. };
  59423. /**
  59424. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59425. * @param url New url.
  59426. */
  59427. VideoTexture.prototype.updateURL = function (url) {
  59428. this.video.src = url;
  59429. };
  59430. VideoTexture.prototype.dispose = function () {
  59431. _super.prototype.dispose.call(this);
  59432. this.video.removeEventListener("canplay", this._createInternalTexture);
  59433. this.video.removeEventListener("paused", this._updateInternalTexture);
  59434. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59435. this.video.removeEventListener("emptied", this.reset);
  59436. this.video.pause();
  59437. };
  59438. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59439. var video = document.createElement("video");
  59440. var constraintsDeviceId;
  59441. if (constraints && constraints.deviceId) {
  59442. constraintsDeviceId = {
  59443. exact: constraints.deviceId,
  59444. };
  59445. }
  59446. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59447. if (navigator.mediaDevices) {
  59448. navigator.mediaDevices.getUserMedia({ video: constraints })
  59449. .then(function (stream) {
  59450. if (video.mozSrcObject !== undefined) {
  59451. // hack for Firefox < 19
  59452. video.mozSrcObject = stream;
  59453. }
  59454. else {
  59455. video.srcObject = stream;
  59456. }
  59457. var onPlaying = function () {
  59458. if (onReady) {
  59459. onReady(new VideoTexture("video", video, scene, true, true));
  59460. }
  59461. video.removeEventListener("playing", onPlaying);
  59462. };
  59463. video.addEventListener("playing", onPlaying);
  59464. video.play();
  59465. })
  59466. .catch(function (err) {
  59467. BABYLON.Tools.Error(err.name);
  59468. });
  59469. }
  59470. else {
  59471. navigator.getUserMedia =
  59472. navigator.getUserMedia ||
  59473. navigator.webkitGetUserMedia ||
  59474. navigator.mozGetUserMedia ||
  59475. navigator.msGetUserMedia;
  59476. if (navigator.getUserMedia) {
  59477. navigator.getUserMedia({
  59478. video: {
  59479. deviceId: constraintsDeviceId,
  59480. width: {
  59481. min: (constraints && constraints.minWidth) || 256,
  59482. max: (constraints && constraints.maxWidth) || 640,
  59483. },
  59484. height: {
  59485. min: (constraints && constraints.minHeight) || 256,
  59486. max: (constraints && constraints.maxHeight) || 480,
  59487. },
  59488. },
  59489. }, function (stream) {
  59490. if (video.mozSrcObject !== undefined) {
  59491. // hack for Firefox < 19
  59492. video.mozSrcObject = stream;
  59493. }
  59494. else {
  59495. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59496. }
  59497. video.play();
  59498. if (onReady) {
  59499. onReady(new VideoTexture("video", video, scene, true, true));
  59500. }
  59501. }, function (e) {
  59502. BABYLON.Tools.Error(e.name);
  59503. });
  59504. }
  59505. }
  59506. };
  59507. return VideoTexture;
  59508. }(BABYLON.Texture));
  59509. BABYLON.VideoTexture = VideoTexture;
  59510. })(BABYLON || (BABYLON = {}));
  59511. //# sourceMappingURL=babylon.videoTexture.js.map
  59512. var BABYLON;
  59513. (function (BABYLON) {
  59514. var RawTexture = /** @class */ (function (_super) {
  59515. __extends(RawTexture, _super);
  59516. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  59517. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59518. if (invertY === void 0) { invertY = false; }
  59519. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59520. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59521. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59522. _this.format = format;
  59523. _this._engine = scene.getEngine();
  59524. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  59525. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59526. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59527. return _this;
  59528. }
  59529. RawTexture.prototype.update = function (data) {
  59530. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  59531. };
  59532. // Statics
  59533. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59534. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59535. if (invertY === void 0) { invertY = false; }
  59536. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59537. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  59538. };
  59539. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59540. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59541. if (invertY === void 0) { invertY = false; }
  59542. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59543. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59544. };
  59545. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59546. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59547. if (invertY === void 0) { invertY = false; }
  59548. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59549. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59550. };
  59551. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59552. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59553. if (invertY === void 0) { invertY = false; }
  59554. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59555. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59556. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  59557. };
  59558. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59559. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59560. if (invertY === void 0) { invertY = false; }
  59561. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59562. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59563. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  59564. };
  59565. return RawTexture;
  59566. }(BABYLON.Texture));
  59567. BABYLON.RawTexture = RawTexture;
  59568. })(BABYLON || (BABYLON = {}));
  59569. //# sourceMappingURL=babylon.rawTexture.js.map
  59570. var BABYLON;
  59571. (function (BABYLON) {
  59572. /**
  59573. * PostProcess can be used to apply a shader to a texture after it has been rendered
  59574. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  59575. */
  59576. var PostProcess = /** @class */ (function () {
  59577. /**
  59578. * Creates a new instance of @see PostProcess
  59579. * @param name The name of the PostProcess.
  59580. * @param fragmentUrl The url of the fragment shader to be used.
  59581. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  59582. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  59583. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  59584. * @param camera The camera to apply the render pass to.
  59585. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  59586. * @param engine The engine which the post process will be applied. (default: current engine)
  59587. * @param reusable If the post process can be reused on the same frame. (default: false)
  59588. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  59589. * @param textureType Type of textures used when performing the post process. (default: 0)
  59590. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  59591. * @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
  59592. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  59593. */
  59594. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  59595. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  59596. if (defines === void 0) { defines = null; }
  59597. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59598. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  59599. if (blockCompilation === void 0) { blockCompilation = false; }
  59600. this.name = name;
  59601. /**
  59602. * Width of the texture to apply the post process on
  59603. */
  59604. this.width = -1;
  59605. /**
  59606. * Height of the texture to apply the post process on
  59607. */
  59608. this.height = -1;
  59609. /**
  59610. * If the buffer needs to be cleared before applying the post process. (default: true)
  59611. * Should be set to false if shader will overwrite all previous pixels.
  59612. */
  59613. this.autoClear = true;
  59614. /**
  59615. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59616. */
  59617. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  59618. /**
  59619. * Animations to be used for the post processing
  59620. */
  59621. this.animations = new Array();
  59622. /**
  59623. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  59624. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  59625. */
  59626. this.enablePixelPerfectMode = false;
  59627. /**
  59628. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  59629. */
  59630. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  59631. /**
  59632. * Force textures to be a power of two (default: false)
  59633. */
  59634. this.alwaysForcePOT = false;
  59635. /**
  59636. * Number of sample textures (default: 1)
  59637. */
  59638. this.samples = 1;
  59639. /**
  59640. * Modify the scale of the post process to be the same as the viewport (default: false)
  59641. */
  59642. this.adaptScaleToCurrentViewport = false;
  59643. this._reusable = false;
  59644. /**
  59645. * Smart array of input and output textures for the post process.
  59646. */
  59647. this._textures = new BABYLON.SmartArray(2);
  59648. /**
  59649. * The index in _textures that corresponds to the output texture.
  59650. */
  59651. this._currentRenderTextureInd = 0;
  59652. this._scaleRatio = new BABYLON.Vector2(1, 1);
  59653. this._texelSize = BABYLON.Vector2.Zero();
  59654. // Events
  59655. /**
  59656. * An event triggered when the postprocess is activated.
  59657. * @type {BABYLON.Observable}
  59658. */
  59659. this.onActivateObservable = new BABYLON.Observable();
  59660. /**
  59661. * An event triggered when the postprocess changes its size.
  59662. * @type {BABYLON.Observable}
  59663. */
  59664. this.onSizeChangedObservable = new BABYLON.Observable();
  59665. /**
  59666. * An event triggered when the postprocess applies its effect.
  59667. * @type {BABYLON.Observable}
  59668. */
  59669. this.onApplyObservable = new BABYLON.Observable();
  59670. /**
  59671. * An event triggered before rendering the postprocess
  59672. * @type {BABYLON.Observable}
  59673. */
  59674. this.onBeforeRenderObservable = new BABYLON.Observable();
  59675. /**
  59676. * An event triggered after rendering the postprocess
  59677. * @type {BABYLON.Observable}
  59678. */
  59679. this.onAfterRenderObservable = new BABYLON.Observable();
  59680. if (camera != null) {
  59681. this._camera = camera;
  59682. this._scene = camera.getScene();
  59683. camera.attachPostProcess(this);
  59684. this._engine = this._scene.getEngine();
  59685. this._scene.postProcesses.push(this);
  59686. }
  59687. else if (engine) {
  59688. this._engine = engine;
  59689. this._engine.postProcesses.push(this);
  59690. }
  59691. this._options = options;
  59692. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59693. this._reusable = reusable || false;
  59694. this._textureType = textureType;
  59695. this._samplers = samplers || [];
  59696. this._samplers.push("textureSampler");
  59697. this._fragmentUrl = fragmentUrl;
  59698. this._vertexUrl = vertexUrl;
  59699. this._parameters = parameters || [];
  59700. this._parameters.push("scale");
  59701. this._indexParameters = indexParameters;
  59702. if (!blockCompilation) {
  59703. this.updateEffect(defines);
  59704. }
  59705. }
  59706. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59707. /**
  59708. * A function that is added to the onActivateObservable
  59709. */
  59710. set: function (callback) {
  59711. if (this._onActivateObserver) {
  59712. this.onActivateObservable.remove(this._onActivateObserver);
  59713. }
  59714. if (callback) {
  59715. this._onActivateObserver = this.onActivateObservable.add(callback);
  59716. }
  59717. },
  59718. enumerable: true,
  59719. configurable: true
  59720. });
  59721. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59722. /**
  59723. * A function that is added to the onSizeChangedObservable
  59724. */
  59725. set: function (callback) {
  59726. if (this._onSizeChangedObserver) {
  59727. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59728. }
  59729. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59730. },
  59731. enumerable: true,
  59732. configurable: true
  59733. });
  59734. Object.defineProperty(PostProcess.prototype, "onApply", {
  59735. /**
  59736. * A function that is added to the onApplyObservable
  59737. */
  59738. set: function (callback) {
  59739. if (this._onApplyObserver) {
  59740. this.onApplyObservable.remove(this._onApplyObserver);
  59741. }
  59742. this._onApplyObserver = this.onApplyObservable.add(callback);
  59743. },
  59744. enumerable: true,
  59745. configurable: true
  59746. });
  59747. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59748. /**
  59749. * A function that is added to the onBeforeRenderObservable
  59750. */
  59751. set: function (callback) {
  59752. if (this._onBeforeRenderObserver) {
  59753. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59754. }
  59755. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59756. },
  59757. enumerable: true,
  59758. configurable: true
  59759. });
  59760. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59761. /**
  59762. * A function that is added to the onAfterRenderObservable
  59763. */
  59764. set: function (callback) {
  59765. if (this._onAfterRenderObserver) {
  59766. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59767. }
  59768. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59769. },
  59770. enumerable: true,
  59771. configurable: true
  59772. });
  59773. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59774. /**
  59775. * 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
  59776. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59777. */
  59778. get: function () {
  59779. return this._textures.data[this._currentRenderTextureInd];
  59780. },
  59781. set: function (value) {
  59782. this._forcedOutputTexture = value;
  59783. },
  59784. enumerable: true,
  59785. configurable: true
  59786. });
  59787. /**
  59788. * Gets the camera which post process is applied to.
  59789. * @returns The camera the post process is applied to.
  59790. */
  59791. PostProcess.prototype.getCamera = function () {
  59792. return this._camera;
  59793. };
  59794. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59795. /**
  59796. * Gets the texel size of the postprocess.
  59797. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59798. */
  59799. get: function () {
  59800. if (this._shareOutputWithPostProcess) {
  59801. return this._shareOutputWithPostProcess.texelSize;
  59802. }
  59803. if (this._forcedOutputTexture) {
  59804. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59805. }
  59806. return this._texelSize;
  59807. },
  59808. enumerable: true,
  59809. configurable: true
  59810. });
  59811. /**
  59812. * Gets the engine which this post process belongs to.
  59813. * @returns The engine the post process was enabled with.
  59814. */
  59815. PostProcess.prototype.getEngine = function () {
  59816. return this._engine;
  59817. };
  59818. /**
  59819. * The effect that is created when initializing the post process.
  59820. * @returns The created effect corrisponding the the postprocess.
  59821. */
  59822. PostProcess.prototype.getEffect = function () {
  59823. return this._effect;
  59824. };
  59825. /**
  59826. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59827. * @param postProcess The post process to share the output with.
  59828. * @returns This post process.
  59829. */
  59830. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59831. this._disposeTextures();
  59832. this._shareOutputWithPostProcess = postProcess;
  59833. return this;
  59834. };
  59835. /**
  59836. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  59837. * This should be called if the post process that shares output with this post process is disabled/disposed.
  59838. */
  59839. PostProcess.prototype.useOwnOutput = function () {
  59840. if (this._textures.length == 0) {
  59841. this._textures = new BABYLON.SmartArray(2);
  59842. }
  59843. this._shareOutputWithPostProcess = null;
  59844. };
  59845. /**
  59846. * Updates the effect with the current post process compile time values and recompiles the shader.
  59847. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59848. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59849. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59850. * @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
  59851. * @param onCompiled Called when the shader has been compiled.
  59852. * @param onError Called if there is an error when compiling a shader.
  59853. */
  59854. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59855. if (defines === void 0) { defines = null; }
  59856. if (uniforms === void 0) { uniforms = null; }
  59857. if (samplers === void 0) { samplers = null; }
  59858. 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);
  59859. };
  59860. /**
  59861. * The post process is reusable if it can be used multiple times within one frame.
  59862. * @returns If the post process is reusable
  59863. */
  59864. PostProcess.prototype.isReusable = function () {
  59865. return this._reusable;
  59866. };
  59867. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59868. PostProcess.prototype.markTextureDirty = function () {
  59869. this.width = -1;
  59870. };
  59871. /**
  59872. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59873. * 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.
  59874. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59875. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59876. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59877. */
  59878. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59879. var _this = this;
  59880. if (sourceTexture === void 0) { sourceTexture = null; }
  59881. camera = camera || this._camera;
  59882. var scene = camera.getScene();
  59883. var engine = scene.getEngine();
  59884. var maxSize = engine.getCaps().maxTextureSize;
  59885. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59886. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59887. // 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
  59888. var webVRCamera = camera.parent;
  59889. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59890. requiredWidth /= 2;
  59891. }
  59892. var desiredWidth = (this._options.width || requiredWidth);
  59893. var desiredHeight = this._options.height || requiredHeight;
  59894. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59895. if (this.adaptScaleToCurrentViewport) {
  59896. var currentViewport = engine.currentViewport;
  59897. if (currentViewport) {
  59898. desiredWidth *= currentViewport.width;
  59899. desiredHeight *= currentViewport.height;
  59900. }
  59901. }
  59902. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59903. if (!this._options.width) {
  59904. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59905. }
  59906. if (!this._options.height) {
  59907. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59908. }
  59909. }
  59910. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59911. if (this._textures.length > 0) {
  59912. for (var i = 0; i < this._textures.length; i++) {
  59913. this._engine._releaseTexture(this._textures.data[i]);
  59914. }
  59915. this._textures.reset();
  59916. }
  59917. this.width = desiredWidth;
  59918. this.height = desiredHeight;
  59919. var textureSize = { width: this.width, height: this.height };
  59920. var textureOptions = {
  59921. generateMipMaps: false,
  59922. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59923. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59924. samplingMode: this.renderTargetSamplingMode,
  59925. type: this._textureType
  59926. };
  59927. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59928. if (this._reusable) {
  59929. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59930. }
  59931. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59932. this.onSizeChangedObservable.notifyObservers(this);
  59933. }
  59934. this._textures.forEach(function (texture) {
  59935. if (texture.samples !== _this.samples) {
  59936. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59937. }
  59938. });
  59939. }
  59940. var target;
  59941. if (this._shareOutputWithPostProcess) {
  59942. target = this._shareOutputWithPostProcess.inputTexture;
  59943. }
  59944. else if (this._forcedOutputTexture) {
  59945. target = this._forcedOutputTexture;
  59946. this.width = this._forcedOutputTexture.width;
  59947. this.height = this._forcedOutputTexture.height;
  59948. }
  59949. else {
  59950. target = this.inputTexture;
  59951. }
  59952. // Bind the input of this post process to be used as the output of the previous post process.
  59953. if (this.enablePixelPerfectMode) {
  59954. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59955. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59956. }
  59957. else {
  59958. this._scaleRatio.copyFromFloats(1, 1);
  59959. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59960. }
  59961. this.onActivateObservable.notifyObservers(camera);
  59962. // Clear
  59963. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59964. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59965. }
  59966. if (this._reusable) {
  59967. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59968. }
  59969. };
  59970. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59971. /**
  59972. * If the post process is supported.
  59973. */
  59974. get: function () {
  59975. return this._effect.isSupported;
  59976. },
  59977. enumerable: true,
  59978. configurable: true
  59979. });
  59980. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59981. /**
  59982. * The aspect ratio of the output texture.
  59983. */
  59984. get: function () {
  59985. if (this._shareOutputWithPostProcess) {
  59986. return this._shareOutputWithPostProcess.aspectRatio;
  59987. }
  59988. if (this._forcedOutputTexture) {
  59989. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59990. }
  59991. return this.width / this.height;
  59992. },
  59993. enumerable: true,
  59994. configurable: true
  59995. });
  59996. /**
  59997. * Get a value indicating if the post-process is ready to be used
  59998. * @returns true if the post-process is ready (shader is compiled)
  59999. */
  60000. PostProcess.prototype.isReady = function () {
  60001. return this._effect && this._effect.isReady();
  60002. };
  60003. /**
  60004. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60005. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60006. */
  60007. PostProcess.prototype.apply = function () {
  60008. // Check
  60009. if (!this._effect || !this._effect.isReady())
  60010. return null;
  60011. // States
  60012. this._engine.enableEffect(this._effect);
  60013. this._engine.setState(false);
  60014. this._engine.setDepthBuffer(false);
  60015. this._engine.setDepthWrite(false);
  60016. // Alpha
  60017. this._engine.setAlphaMode(this.alphaMode);
  60018. if (this.alphaConstants) {
  60019. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60020. }
  60021. // Bind the output texture of the preivous post process as the input to this post process.
  60022. var source;
  60023. if (this._shareOutputWithPostProcess) {
  60024. source = this._shareOutputWithPostProcess.inputTexture;
  60025. }
  60026. else if (this._forcedOutputTexture) {
  60027. source = this._forcedOutputTexture;
  60028. }
  60029. else {
  60030. source = this.inputTexture;
  60031. }
  60032. this._effect._bindTexture("textureSampler", source);
  60033. // Parameters
  60034. this._effect.setVector2("scale", this._scaleRatio);
  60035. this.onApplyObservable.notifyObservers(this._effect);
  60036. return this._effect;
  60037. };
  60038. PostProcess.prototype._disposeTextures = function () {
  60039. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60040. return;
  60041. }
  60042. if (this._textures.length > 0) {
  60043. for (var i = 0; i < this._textures.length; i++) {
  60044. this._engine._releaseTexture(this._textures.data[i]);
  60045. }
  60046. }
  60047. this._textures.dispose();
  60048. };
  60049. /**
  60050. * Disposes the post process.
  60051. * @param camera The camera to dispose the post process on.
  60052. */
  60053. PostProcess.prototype.dispose = function (camera) {
  60054. camera = camera || this._camera;
  60055. this._disposeTextures();
  60056. if (this._scene) {
  60057. var index_1 = this._scene.postProcesses.indexOf(this);
  60058. if (index_1 !== -1) {
  60059. this._scene.postProcesses.splice(index_1, 1);
  60060. }
  60061. }
  60062. else {
  60063. var index_2 = this._engine.postProcesses.indexOf(this);
  60064. if (index_2 !== -1) {
  60065. this._engine.postProcesses.splice(index_2, 1);
  60066. }
  60067. }
  60068. if (!camera) {
  60069. return;
  60070. }
  60071. camera.detachPostProcess(this);
  60072. var index = camera._postProcesses.indexOf(this);
  60073. if (index === 0 && camera._postProcesses.length > 0) {
  60074. var firstPostProcess = this._camera._getFirstPostProcess();
  60075. if (firstPostProcess) {
  60076. firstPostProcess.markTextureDirty();
  60077. }
  60078. }
  60079. this.onActivateObservable.clear();
  60080. this.onAfterRenderObservable.clear();
  60081. this.onApplyObservable.clear();
  60082. this.onBeforeRenderObservable.clear();
  60083. this.onSizeChangedObservable.clear();
  60084. };
  60085. return PostProcess;
  60086. }());
  60087. BABYLON.PostProcess = PostProcess;
  60088. })(BABYLON || (BABYLON = {}));
  60089. //# sourceMappingURL=babylon.postProcess.js.map
  60090. var BABYLON;
  60091. (function (BABYLON) {
  60092. var PassPostProcess = /** @class */ (function (_super) {
  60093. __extends(PassPostProcess, _super);
  60094. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60095. if (camera === void 0) { camera = null; }
  60096. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60097. if (blockCompilation === void 0) { blockCompilation = false; }
  60098. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60099. }
  60100. return PassPostProcess;
  60101. }(BABYLON.PostProcess));
  60102. BABYLON.PassPostProcess = PassPostProcess;
  60103. })(BABYLON || (BABYLON = {}));
  60104. //# sourceMappingURL=babylon.passPostProcess.js.map
  60105. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60106. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60107. s = arguments[i];
  60108. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60109. t[p] = s[p];
  60110. }
  60111. return t;
  60112. };
  60113. var BABYLON;
  60114. (function (BABYLON) {
  60115. /**
  60116. * Default implementation of @see IShadowGenerator.
  60117. * This is the main object responsible of generating shadows in the framework.
  60118. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60119. */
  60120. var ShadowGenerator = /** @class */ (function () {
  60121. /**
  60122. * Creates a ShadowGenerator object.
  60123. * A ShadowGenerator is the required tool to use the shadows.
  60124. * Each light casting shadows needs to use its own ShadowGenerator.
  60125. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60126. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60127. * @param light The light object generating the shadows.
  60128. * @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.
  60129. */
  60130. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60131. this._bias = 0.00005;
  60132. this._blurBoxOffset = 1;
  60133. this._blurScale = 2;
  60134. this._blurKernel = 1;
  60135. this._useKernelBlur = false;
  60136. this._filter = ShadowGenerator.FILTER_NONE;
  60137. this._darkness = 0;
  60138. this._transparencyShadow = false;
  60139. /**
  60140. * Controls the extent to which the shadows fade out at the edge of the frustum
  60141. * Used only by directionals and spots
  60142. */
  60143. this.frustumEdgeFalloff = 0;
  60144. /**
  60145. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60146. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60147. * It might on the other hand introduce peter panning.
  60148. */
  60149. this.forceBackFacesOnly = false;
  60150. this._lightDirection = BABYLON.Vector3.Zero();
  60151. this._viewMatrix = BABYLON.Matrix.Zero();
  60152. this._projectionMatrix = BABYLON.Matrix.Zero();
  60153. this._transformMatrix = BABYLON.Matrix.Zero();
  60154. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60155. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60156. this._currentFaceIndex = 0;
  60157. this._currentFaceIndexCache = 0;
  60158. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60159. this._mapSize = mapSize;
  60160. this._light = light;
  60161. this._scene = light.getScene();
  60162. light._shadowGenerator = this;
  60163. // Texture type fallback from float to int if not supported.
  60164. var caps = this._scene.getEngine().getCaps();
  60165. if (!useFullFloatFirst) {
  60166. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60167. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60168. }
  60169. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60170. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60171. }
  60172. else {
  60173. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60174. }
  60175. }
  60176. else {
  60177. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60178. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60179. }
  60180. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60181. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60182. }
  60183. else {
  60184. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60185. }
  60186. }
  60187. this._initializeGenerator();
  60188. }
  60189. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  60190. /**
  60191. * Shadow generator mode None: no filtering applied.
  60192. */
  60193. get: function () {
  60194. return ShadowGenerator._FILTER_NONE;
  60195. },
  60196. enumerable: true,
  60197. configurable: true
  60198. });
  60199. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  60200. /**
  60201. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  60202. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  60203. */
  60204. get: function () {
  60205. return ShadowGenerator._FILTER_POISSONSAMPLING;
  60206. },
  60207. enumerable: true,
  60208. configurable: true
  60209. });
  60210. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  60211. /**
  60212. * Shadow generator mode ESM: Exponential Shadow Mapping.
  60213. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60214. */
  60215. get: function () {
  60216. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  60217. },
  60218. enumerable: true,
  60219. configurable: true
  60220. });
  60221. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  60222. /**
  60223. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  60224. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60225. */
  60226. get: function () {
  60227. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  60228. },
  60229. enumerable: true,
  60230. configurable: true
  60231. });
  60232. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  60233. /**
  60234. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  60235. * edge artifacts on steep falloff.
  60236. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60237. */
  60238. get: function () {
  60239. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60240. },
  60241. enumerable: true,
  60242. configurable: true
  60243. });
  60244. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  60245. /**
  60246. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  60247. * edge artifacts on steep falloff.
  60248. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60249. */
  60250. get: function () {
  60251. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60252. },
  60253. enumerable: true,
  60254. configurable: true
  60255. });
  60256. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60257. /**
  60258. * Gets the bias: offset applied on the depth preventing acnea.
  60259. */
  60260. get: function () {
  60261. return this._bias;
  60262. },
  60263. /**
  60264. * Sets the bias: offset applied on the depth preventing acnea.
  60265. */
  60266. set: function (bias) {
  60267. this._bias = bias;
  60268. },
  60269. enumerable: true,
  60270. configurable: true
  60271. });
  60272. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60273. /**
  60274. * Gets the blur box offset: offset applied during the blur pass.
  60275. * Only usefull if useKernelBlur = false
  60276. */
  60277. get: function () {
  60278. return this._blurBoxOffset;
  60279. },
  60280. /**
  60281. * Sets the blur box offset: offset applied during the blur pass.
  60282. * Only usefull if useKernelBlur = false
  60283. */
  60284. set: function (value) {
  60285. if (this._blurBoxOffset === value) {
  60286. return;
  60287. }
  60288. this._blurBoxOffset = value;
  60289. this._disposeBlurPostProcesses();
  60290. },
  60291. enumerable: true,
  60292. configurable: true
  60293. });
  60294. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60295. /**
  60296. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60297. * 2 means half of the size.
  60298. */
  60299. get: function () {
  60300. return this._blurScale;
  60301. },
  60302. /**
  60303. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60304. * 2 means half of the size.
  60305. */
  60306. set: function (value) {
  60307. if (this._blurScale === value) {
  60308. return;
  60309. }
  60310. this._blurScale = value;
  60311. this._disposeBlurPostProcesses();
  60312. },
  60313. enumerable: true,
  60314. configurable: true
  60315. });
  60316. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  60317. /**
  60318. * Gets the blur kernel: kernel size of the blur pass.
  60319. * Only usefull if useKernelBlur = true
  60320. */
  60321. get: function () {
  60322. return this._blurKernel;
  60323. },
  60324. /**
  60325. * Sets the blur kernel: kernel size of the blur pass.
  60326. * Only usefull if useKernelBlur = true
  60327. */
  60328. set: function (value) {
  60329. if (this._blurKernel === value) {
  60330. return;
  60331. }
  60332. this._blurKernel = value;
  60333. this._disposeBlurPostProcesses();
  60334. },
  60335. enumerable: true,
  60336. configurable: true
  60337. });
  60338. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  60339. /**
  60340. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  60341. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60342. */
  60343. get: function () {
  60344. return this._useKernelBlur;
  60345. },
  60346. /**
  60347. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  60348. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60349. */
  60350. set: function (value) {
  60351. if (this._useKernelBlur === value) {
  60352. return;
  60353. }
  60354. this._useKernelBlur = value;
  60355. this._disposeBlurPostProcesses();
  60356. },
  60357. enumerable: true,
  60358. configurable: true
  60359. });
  60360. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  60361. /**
  60362. * Gets the depth scale used in ESM mode.
  60363. */
  60364. get: function () {
  60365. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  60366. },
  60367. /**
  60368. * Sets the depth scale used in ESM mode.
  60369. * This can override the scale stored on the light.
  60370. */
  60371. set: function (value) {
  60372. this._depthScale = value;
  60373. },
  60374. enumerable: true,
  60375. configurable: true
  60376. });
  60377. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  60378. /**
  60379. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  60380. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60381. */
  60382. get: function () {
  60383. return this._filter;
  60384. },
  60385. /**
  60386. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  60387. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60388. */
  60389. set: function (value) {
  60390. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  60391. if (this._light.needCube()) {
  60392. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60393. this.useExponentialShadowMap = true;
  60394. return;
  60395. }
  60396. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60397. this.useCloseExponentialShadowMap = true;
  60398. return;
  60399. }
  60400. }
  60401. if (this._filter === value) {
  60402. return;
  60403. }
  60404. this._filter = value;
  60405. this._disposeBlurPostProcesses();
  60406. this._applyFilterValues();
  60407. this._light._markMeshesAsLightDirty();
  60408. },
  60409. enumerable: true,
  60410. configurable: true
  60411. });
  60412. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60413. /**
  60414. * Gets if the current filter is set to Poisson Sampling aka PCF.
  60415. */
  60416. get: function () {
  60417. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60418. },
  60419. /**
  60420. * Sets the current filter to Poisson Sampling aka PCF.
  60421. */
  60422. set: function (value) {
  60423. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60424. return;
  60425. }
  60426. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60427. },
  60428. enumerable: true,
  60429. configurable: true
  60430. });
  60431. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60432. /**
  60433. * Gets if the current filter is set to VSM.
  60434. * DEPRECATED. Should use useExponentialShadowMap instead.
  60435. */
  60436. get: function () {
  60437. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60438. return this.useExponentialShadowMap;
  60439. },
  60440. /**
  60441. * Sets the current filter is to VSM.
  60442. * DEPRECATED. Should use useExponentialShadowMap instead.
  60443. */
  60444. set: function (value) {
  60445. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60446. this.useExponentialShadowMap = value;
  60447. },
  60448. enumerable: true,
  60449. configurable: true
  60450. });
  60451. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60452. /**
  60453. * Gets if the current filter is set to blurred VSM.
  60454. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60455. */
  60456. get: function () {
  60457. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60458. return this.useBlurExponentialShadowMap;
  60459. },
  60460. /**
  60461. * Sets the current filter is to blurred VSM.
  60462. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60463. */
  60464. set: function (value) {
  60465. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60466. this.useBlurExponentialShadowMap = value;
  60467. },
  60468. enumerable: true,
  60469. configurable: true
  60470. });
  60471. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60472. /**
  60473. * Gets if the current filter is set to ESM.
  60474. */
  60475. get: function () {
  60476. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60477. },
  60478. /**
  60479. * Sets the current filter is to ESM.
  60480. */
  60481. set: function (value) {
  60482. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60483. return;
  60484. }
  60485. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60486. },
  60487. enumerable: true,
  60488. configurable: true
  60489. });
  60490. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60491. /**
  60492. * Gets if the current filter is set to filtered ESM.
  60493. */
  60494. get: function () {
  60495. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60496. },
  60497. /**
  60498. * Gets if the current filter is set to filtered ESM.
  60499. */
  60500. set: function (value) {
  60501. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60502. return;
  60503. }
  60504. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60505. },
  60506. enumerable: true,
  60507. configurable: true
  60508. });
  60509. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60510. /**
  60511. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60512. * exponential to prevent steep falloff artifacts).
  60513. */
  60514. get: function () {
  60515. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60516. },
  60517. /**
  60518. * Sets the current filter to "close ESM" (using the inverse of the
  60519. * exponential to prevent steep falloff artifacts).
  60520. */
  60521. set: function (value) {
  60522. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60523. return;
  60524. }
  60525. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60526. },
  60527. enumerable: true,
  60528. configurable: true
  60529. });
  60530. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60531. /**
  60532. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60533. * exponential to prevent steep falloff artifacts).
  60534. */
  60535. get: function () {
  60536. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60537. },
  60538. /**
  60539. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  60540. * exponential to prevent steep falloff artifacts).
  60541. */
  60542. set: function (value) {
  60543. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60544. return;
  60545. }
  60546. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60547. },
  60548. enumerable: true,
  60549. configurable: true
  60550. });
  60551. /**
  60552. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  60553. * 0 means strongest and 1 would means no shadow.
  60554. * @returns the darkness.
  60555. */
  60556. ShadowGenerator.prototype.getDarkness = function () {
  60557. return this._darkness;
  60558. };
  60559. /**
  60560. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  60561. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  60562. * @returns the shadow generator allowing fluent coding.
  60563. */
  60564. ShadowGenerator.prototype.setDarkness = function (darkness) {
  60565. if (darkness >= 1.0)
  60566. this._darkness = 1.0;
  60567. else if (darkness <= 0.0)
  60568. this._darkness = 0.0;
  60569. else
  60570. this._darkness = darkness;
  60571. return this;
  60572. };
  60573. /**
  60574. * Sets the ability to have transparent shadow (boolean).
  60575. * @param transparent True if transparent else False
  60576. * @returns the shadow generator allowing fluent coding
  60577. */
  60578. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  60579. this._transparencyShadow = transparent;
  60580. return this;
  60581. };
  60582. /**
  60583. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  60584. * @returns The render target texture if present otherwise, null
  60585. */
  60586. ShadowGenerator.prototype.getShadowMap = function () {
  60587. return this._shadowMap;
  60588. };
  60589. /**
  60590. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  60591. * @returns The render target texture if the shadow map is present otherwise, null
  60592. */
  60593. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  60594. if (this._shadowMap2) {
  60595. return this._shadowMap2;
  60596. }
  60597. return this._shadowMap;
  60598. };
  60599. /**
  60600. * Helper function to add a mesh and its descendants to the list of shadow casters.
  60601. * @param mesh Mesh to add
  60602. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  60603. * @returns the Shadow Generator itself
  60604. */
  60605. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  60606. if (includeDescendants === void 0) { includeDescendants = true; }
  60607. if (!this._shadowMap) {
  60608. return this;
  60609. }
  60610. if (!this._shadowMap.renderList) {
  60611. this._shadowMap.renderList = [];
  60612. }
  60613. this._shadowMap.renderList.push(mesh);
  60614. if (includeDescendants) {
  60615. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  60616. }
  60617. return this;
  60618. var _a;
  60619. };
  60620. /**
  60621. * Helper function to remove a mesh and its descendants from the list of shadow casters
  60622. * @param mesh Mesh to remove
  60623. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  60624. * @returns the Shadow Generator itself
  60625. */
  60626. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  60627. if (includeDescendants === void 0) { includeDescendants = true; }
  60628. if (!this._shadowMap || !this._shadowMap.renderList) {
  60629. return this;
  60630. }
  60631. var index = this._shadowMap.renderList.indexOf(mesh);
  60632. if (index !== -1) {
  60633. this._shadowMap.renderList.splice(index, 1);
  60634. }
  60635. if (includeDescendants) {
  60636. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  60637. var child = _a[_i];
  60638. this.removeShadowCaster(child);
  60639. }
  60640. }
  60641. return this;
  60642. };
  60643. /**
  60644. * Returns the associated light object.
  60645. * @returns the light generating the shadow
  60646. */
  60647. ShadowGenerator.prototype.getLight = function () {
  60648. return this._light;
  60649. };
  60650. ShadowGenerator.prototype._initializeGenerator = function () {
  60651. this._light._markMeshesAsLightDirty();
  60652. this._initializeShadowMap();
  60653. };
  60654. ShadowGenerator.prototype._initializeShadowMap = function () {
  60655. var _this = this;
  60656. // Render target
  60657. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  60658. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60659. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60660. this._shadowMap.anisotropicFilteringLevel = 1;
  60661. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60662. this._shadowMap.renderParticles = false;
  60663. this._shadowMap.ignoreCameraViewport = true;
  60664. // Record Face Index before render.
  60665. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  60666. _this._currentFaceIndex = faceIndex;
  60667. });
  60668. // Custom render function.
  60669. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  60670. // Blur if required afer render.
  60671. this._shadowMap.onAfterUnbindObservable.add(function () {
  60672. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  60673. return;
  60674. }
  60675. var shadowMap = _this.getShadowMapForRendering();
  60676. if (shadowMap) {
  60677. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  60678. }
  60679. });
  60680. // Clear according to the chosen filter.
  60681. var zero = new BABYLON.Color4(0, 0, 0, 0);
  60682. var one = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60683. this._shadowMap.onClearObservable.add(function (engine) {
  60684. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60685. engine.clear(zero, true, true, true);
  60686. }
  60687. else {
  60688. engine.clear(one, true, true, true);
  60689. }
  60690. });
  60691. };
  60692. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60693. var _this = this;
  60694. var engine = this._scene.getEngine();
  60695. var targetSize = this._mapSize / this.blurScale;
  60696. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60697. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60698. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60699. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60700. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60701. }
  60702. if (this.useKernelBlur) {
  60703. 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);
  60704. this._kernelBlurXPostprocess.width = targetSize;
  60705. this._kernelBlurXPostprocess.height = targetSize;
  60706. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60707. effect.setTexture("textureSampler", _this._shadowMap);
  60708. });
  60709. 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);
  60710. this._kernelBlurXPostprocess.autoClear = false;
  60711. this._kernelBlurYPostprocess.autoClear = false;
  60712. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60713. this._kernelBlurXPostprocess.packedFloat = true;
  60714. this._kernelBlurYPostprocess.packedFloat = true;
  60715. }
  60716. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60717. }
  60718. else {
  60719. 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);
  60720. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60721. effect.setFloat2("screenSize", targetSize, targetSize);
  60722. effect.setTexture("textureSampler", _this._shadowMap);
  60723. });
  60724. this._boxBlurPostprocess.autoClear = false;
  60725. this._blurPostProcesses = [this._boxBlurPostprocess];
  60726. }
  60727. };
  60728. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60729. var index;
  60730. var engine = this._scene.getEngine();
  60731. if (depthOnlySubMeshes.length) {
  60732. engine.setColorWrite(false);
  60733. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60734. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60735. }
  60736. engine.setColorWrite(true);
  60737. }
  60738. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60739. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60740. }
  60741. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60742. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60743. }
  60744. if (this._transparencyShadow) {
  60745. for (index = 0; index < transparentSubMeshes.length; index++) {
  60746. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60747. }
  60748. }
  60749. };
  60750. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60751. var _this = this;
  60752. var mesh = subMesh.getRenderingMesh();
  60753. var scene = this._scene;
  60754. var engine = scene.getEngine();
  60755. var material = subMesh.getMaterial();
  60756. if (!material) {
  60757. return;
  60758. }
  60759. // Culling
  60760. engine.setState(material.backFaceCulling);
  60761. // Managing instances
  60762. var batch = mesh._getInstancesRenderList(subMesh._id);
  60763. if (batch.mustReturn) {
  60764. return;
  60765. }
  60766. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60767. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60768. engine.enableEffect(this._effect);
  60769. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60770. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  60771. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60772. this._effect.setVector3("lightPosition", this.getLight().position);
  60773. if (scene.activeCamera) {
  60774. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60775. }
  60776. // Alpha test
  60777. if (material && material.needAlphaTesting()) {
  60778. var alphaTexture = material.getAlphaTestTexture();
  60779. if (alphaTexture) {
  60780. this._effect.setTexture("diffuseSampler", alphaTexture);
  60781. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60782. }
  60783. }
  60784. // Bones
  60785. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60786. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60787. }
  60788. if (this.forceBackFacesOnly) {
  60789. engine.setState(true, 0, false, true);
  60790. }
  60791. // Draw
  60792. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60793. if (this.forceBackFacesOnly) {
  60794. engine.setState(true, 0, false, false);
  60795. }
  60796. }
  60797. else {
  60798. // Need to reset refresh rate of the shadowMap
  60799. if (this._shadowMap) {
  60800. this._shadowMap.resetRefreshCounter();
  60801. }
  60802. }
  60803. };
  60804. ShadowGenerator.prototype._applyFilterValues = function () {
  60805. if (!this._shadowMap) {
  60806. return;
  60807. }
  60808. if (this.filter === ShadowGenerator.FILTER_NONE) {
  60809. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60810. }
  60811. else {
  60812. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60813. }
  60814. };
  60815. /**
  60816. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60817. * @param onCompiled Callback triggered at the and of the effects compilation
  60818. * @param options Sets of optional options forcing the compilation with different modes
  60819. */
  60820. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60821. var _this = this;
  60822. var localOptions = __assign({ useInstances: false }, options);
  60823. var shadowMap = this.getShadowMap();
  60824. if (!shadowMap) {
  60825. if (onCompiled) {
  60826. onCompiled(this);
  60827. }
  60828. return;
  60829. }
  60830. var renderList = shadowMap.renderList;
  60831. if (!renderList) {
  60832. if (onCompiled) {
  60833. onCompiled(this);
  60834. }
  60835. return;
  60836. }
  60837. var subMeshes = new Array();
  60838. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60839. var mesh = renderList_1[_i];
  60840. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60841. }
  60842. if (subMeshes.length === 0) {
  60843. if (onCompiled) {
  60844. onCompiled(this);
  60845. }
  60846. return;
  60847. }
  60848. var currentIndex = 0;
  60849. var checkReady = function () {
  60850. if (!_this._scene || !_this._scene.getEngine()) {
  60851. return;
  60852. }
  60853. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60854. currentIndex++;
  60855. if (currentIndex >= subMeshes.length) {
  60856. if (onCompiled) {
  60857. onCompiled(_this);
  60858. }
  60859. return;
  60860. }
  60861. }
  60862. setTimeout(checkReady, 16);
  60863. };
  60864. checkReady();
  60865. };
  60866. /**
  60867. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60868. * @param options Sets of optional options forcing the compilation with different modes
  60869. * @returns A promise that resolves when the compilation completes
  60870. */
  60871. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60872. var _this = this;
  60873. return new Promise(function (resolve) {
  60874. _this.forceCompilation(function () {
  60875. resolve();
  60876. }, options);
  60877. });
  60878. };
  60879. /**
  60880. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60881. * @param subMesh The submesh we want to render in the shadow map
  60882. * @param useInstances Defines wether will draw in the map using instances
  60883. * @returns true if ready otherwise, false
  60884. */
  60885. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60886. var defines = [];
  60887. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60888. defines.push("#define FLOAT");
  60889. }
  60890. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60891. defines.push("#define ESM");
  60892. }
  60893. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60894. var mesh = subMesh.getMesh();
  60895. var material = subMesh.getMaterial();
  60896. // Alpha test
  60897. if (material && material.needAlphaTesting()) {
  60898. var alphaTexture = material.getAlphaTestTexture();
  60899. if (alphaTexture) {
  60900. defines.push("#define ALPHATEST");
  60901. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60902. attribs.push(BABYLON.VertexBuffer.UVKind);
  60903. defines.push("#define UV1");
  60904. }
  60905. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60906. if (alphaTexture.coordinatesIndex === 1) {
  60907. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60908. defines.push("#define UV2");
  60909. }
  60910. }
  60911. }
  60912. }
  60913. // Bones
  60914. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60915. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60916. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60917. if (mesh.numBoneInfluencers > 4) {
  60918. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60919. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60920. }
  60921. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60922. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60923. }
  60924. else {
  60925. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60926. }
  60927. // Instances
  60928. if (useInstances) {
  60929. defines.push("#define INSTANCES");
  60930. attribs.push("world0");
  60931. attribs.push("world1");
  60932. attribs.push("world2");
  60933. attribs.push("world3");
  60934. }
  60935. // Get correct effect
  60936. var join = defines.join("\n");
  60937. if (this._cachedDefines !== join) {
  60938. this._cachedDefines = join;
  60939. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60940. }
  60941. if (!this._effect.isReady()) {
  60942. return false;
  60943. }
  60944. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60945. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60946. this._initializeBlurRTTAndPostProcesses();
  60947. }
  60948. }
  60949. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60950. return false;
  60951. }
  60952. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60953. return false;
  60954. }
  60955. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60956. return false;
  60957. }
  60958. return true;
  60959. };
  60960. /**
  60961. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60962. * @param defines Defines of the material we want to update
  60963. * @param lightIndex Index of the light in the enabled light list of the material
  60964. */
  60965. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60966. var scene = this._scene;
  60967. var light = this._light;
  60968. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60969. return;
  60970. }
  60971. defines["SHADOW" + lightIndex] = true;
  60972. if (this.usePoissonSampling) {
  60973. defines["SHADOWPCF" + lightIndex] = true;
  60974. }
  60975. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60976. defines["SHADOWESM" + lightIndex] = true;
  60977. }
  60978. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60979. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60980. }
  60981. if (light.needCube()) {
  60982. defines["SHADOWCUBE" + lightIndex] = true;
  60983. }
  60984. };
  60985. /**
  60986. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60987. * defined in the generator but impacting the effect).
  60988. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60989. * @param effect The effect we are binfing the information for
  60990. */
  60991. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60992. var light = this._light;
  60993. var scene = this._scene;
  60994. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60995. return;
  60996. }
  60997. var camera = scene.activeCamera;
  60998. if (!camera) {
  60999. return;
  61000. }
  61001. var shadowMap = this.getShadowMap();
  61002. if (!shadowMap) {
  61003. return;
  61004. }
  61005. if (!light.needCube()) {
  61006. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61007. }
  61008. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61009. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61010. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61011. };
  61012. /**
  61013. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61014. * (eq to shadow prjection matrix * light transform matrix)
  61015. * @returns The transform matrix used to create the shadow map
  61016. */
  61017. ShadowGenerator.prototype.getTransformMatrix = function () {
  61018. var scene = this._scene;
  61019. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61020. return this._transformMatrix;
  61021. }
  61022. this._currentRenderID = scene.getRenderId();
  61023. this._currentFaceIndexCache = this._currentFaceIndex;
  61024. var lightPosition = this._light.position;
  61025. if (this._light.computeTransformedInformation()) {
  61026. lightPosition = this._light.transformedPosition;
  61027. }
  61028. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61029. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61030. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61031. }
  61032. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61033. this._cachedPosition.copyFrom(lightPosition);
  61034. this._cachedDirection.copyFrom(this._lightDirection);
  61035. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61036. var shadowMap = this.getShadowMap();
  61037. if (shadowMap) {
  61038. var renderList = shadowMap.renderList;
  61039. if (renderList) {
  61040. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61041. }
  61042. }
  61043. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61044. }
  61045. return this._transformMatrix;
  61046. };
  61047. /**
  61048. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61049. * Cube and 2D textures for instance.
  61050. */
  61051. ShadowGenerator.prototype.recreateShadowMap = function () {
  61052. var shadowMap = this._shadowMap;
  61053. if (!shadowMap) {
  61054. return;
  61055. }
  61056. // Track render list.
  61057. var renderList = shadowMap.renderList;
  61058. // Clean up existing data.
  61059. this._disposeRTTandPostProcesses();
  61060. // Reinitializes.
  61061. this._initializeGenerator();
  61062. // Reaffect the filter to ensure a correct fallback if necessary.
  61063. this.filter = this.filter;
  61064. // Reaffect the filter.
  61065. this._applyFilterValues();
  61066. // Reaffect Render List.
  61067. this._shadowMap.renderList = renderList;
  61068. };
  61069. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61070. if (this._shadowMap2) {
  61071. this._shadowMap2.dispose();
  61072. this._shadowMap2 = null;
  61073. }
  61074. if (this._boxBlurPostprocess) {
  61075. this._boxBlurPostprocess.dispose();
  61076. this._boxBlurPostprocess = null;
  61077. }
  61078. if (this._kernelBlurXPostprocess) {
  61079. this._kernelBlurXPostprocess.dispose();
  61080. this._kernelBlurXPostprocess = null;
  61081. }
  61082. if (this._kernelBlurYPostprocess) {
  61083. this._kernelBlurYPostprocess.dispose();
  61084. this._kernelBlurYPostprocess = null;
  61085. }
  61086. this._blurPostProcesses = [];
  61087. };
  61088. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61089. if (this._shadowMap) {
  61090. this._shadowMap.dispose();
  61091. this._shadowMap = null;
  61092. }
  61093. this._disposeBlurPostProcesses();
  61094. };
  61095. /**
  61096. * Disposes the ShadowGenerator.
  61097. * Returns nothing.
  61098. */
  61099. ShadowGenerator.prototype.dispose = function () {
  61100. this._disposeRTTandPostProcesses();
  61101. if (this._light) {
  61102. this._light._shadowGenerator = null;
  61103. this._light._markMeshesAsLightDirty();
  61104. }
  61105. };
  61106. /**
  61107. * Serializes the shadow generator setup to a json object.
  61108. * @returns The serialized JSON object
  61109. */
  61110. ShadowGenerator.prototype.serialize = function () {
  61111. var serializationObject = {};
  61112. var shadowMap = this.getShadowMap();
  61113. if (!shadowMap) {
  61114. return serializationObject;
  61115. }
  61116. serializationObject.lightId = this._light.id;
  61117. serializationObject.mapSize = shadowMap.getRenderSize();
  61118. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  61119. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  61120. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61121. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61122. serializationObject.usePoissonSampling = this.usePoissonSampling;
  61123. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  61124. serializationObject.depthScale = this.depthScale;
  61125. serializationObject.darkness = this.getDarkness();
  61126. serializationObject.blurBoxOffset = this.blurBoxOffset;
  61127. serializationObject.blurKernel = this.blurKernel;
  61128. serializationObject.blurScale = this.blurScale;
  61129. serializationObject.useKernelBlur = this.useKernelBlur;
  61130. serializationObject.transparencyShadow = this._transparencyShadow;
  61131. serializationObject.renderList = [];
  61132. if (shadowMap.renderList) {
  61133. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  61134. var mesh = shadowMap.renderList[meshIndex];
  61135. serializationObject.renderList.push(mesh.id);
  61136. }
  61137. }
  61138. return serializationObject;
  61139. };
  61140. /**
  61141. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  61142. * @param parsedShadowGenerator The JSON object to parse
  61143. * @param scene The scene to create the shadow map for
  61144. * @returns The parsed shadow generator
  61145. */
  61146. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  61147. //casting to point light, as light is missing the position attr and typescript complains.
  61148. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  61149. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  61150. var shadowMap = shadowGenerator.getShadowMap();
  61151. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  61152. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  61153. meshes.forEach(function (mesh) {
  61154. if (!shadowMap) {
  61155. return;
  61156. }
  61157. if (!shadowMap.renderList) {
  61158. shadowMap.renderList = [];
  61159. }
  61160. shadowMap.renderList.push(mesh);
  61161. });
  61162. }
  61163. if (parsedShadowGenerator.usePoissonSampling) {
  61164. shadowGenerator.usePoissonSampling = true;
  61165. }
  61166. else if (parsedShadowGenerator.useExponentialShadowMap) {
  61167. shadowGenerator.useExponentialShadowMap = true;
  61168. }
  61169. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  61170. shadowGenerator.useBlurExponentialShadowMap = true;
  61171. }
  61172. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  61173. shadowGenerator.useCloseExponentialShadowMap = true;
  61174. }
  61175. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  61176. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  61177. }
  61178. else if (parsedShadowGenerator.useVarianceShadowMap) {
  61179. shadowGenerator.useExponentialShadowMap = true;
  61180. }
  61181. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  61182. shadowGenerator.useBlurExponentialShadowMap = true;
  61183. }
  61184. if (parsedShadowGenerator.depthScale) {
  61185. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  61186. }
  61187. if (parsedShadowGenerator.blurScale) {
  61188. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  61189. }
  61190. if (parsedShadowGenerator.blurBoxOffset) {
  61191. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  61192. }
  61193. if (parsedShadowGenerator.useKernelBlur) {
  61194. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  61195. }
  61196. if (parsedShadowGenerator.blurKernel) {
  61197. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  61198. }
  61199. if (parsedShadowGenerator.bias !== undefined) {
  61200. shadowGenerator.bias = parsedShadowGenerator.bias;
  61201. }
  61202. if (parsedShadowGenerator.darkness) {
  61203. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  61204. }
  61205. if (parsedShadowGenerator.transparencyShadow) {
  61206. shadowGenerator.setTransparencyShadow(true);
  61207. }
  61208. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  61209. return shadowGenerator;
  61210. };
  61211. ShadowGenerator._FILTER_NONE = 0;
  61212. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  61213. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  61214. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  61215. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  61216. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  61217. return ShadowGenerator;
  61218. }());
  61219. BABYLON.ShadowGenerator = ShadowGenerator;
  61220. })(BABYLON || (BABYLON = {}));
  61221. //# sourceMappingURL=babylon.shadowGenerator.js.map
  61222. var BABYLON;
  61223. (function (BABYLON) {
  61224. var DefaultLoadingScreen = /** @class */ (function () {
  61225. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  61226. if (_loadingText === void 0) { _loadingText = ""; }
  61227. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  61228. var _this = this;
  61229. this._renderingCanvas = _renderingCanvas;
  61230. this._loadingText = _loadingText;
  61231. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  61232. // Resize
  61233. this._resizeLoadingUI = function () {
  61234. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  61235. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  61236. if (!_this._loadingDiv) {
  61237. return;
  61238. }
  61239. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  61240. _this._loadingDiv.style.left = canvasRect.left + "px";
  61241. _this._loadingDiv.style.top = canvasRect.top + "px";
  61242. _this._loadingDiv.style.width = canvasRect.width + "px";
  61243. _this._loadingDiv.style.height = canvasRect.height + "px";
  61244. };
  61245. }
  61246. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  61247. if (this._loadingDiv) {
  61248. // Do not add a loading screen if there is already one
  61249. return;
  61250. }
  61251. this._loadingDiv = document.createElement("div");
  61252. this._loadingDiv.id = "babylonjsLoadingDiv";
  61253. this._loadingDiv.style.opacity = "0";
  61254. this._loadingDiv.style.transition = "opacity 1.5s ease";
  61255. this._loadingDiv.style.pointerEvents = "none";
  61256. // Loading text
  61257. this._loadingTextDiv = document.createElement("div");
  61258. this._loadingTextDiv.style.position = "absolute";
  61259. this._loadingTextDiv.style.left = "0";
  61260. this._loadingTextDiv.style.top = "50%";
  61261. this._loadingTextDiv.style.marginTop = "80px";
  61262. this._loadingTextDiv.style.width = "100%";
  61263. this._loadingTextDiv.style.height = "20px";
  61264. this._loadingTextDiv.style.fontFamily = "Arial";
  61265. this._loadingTextDiv.style.fontSize = "14px";
  61266. this._loadingTextDiv.style.color = "white";
  61267. this._loadingTextDiv.style.textAlign = "center";
  61268. this._loadingTextDiv.innerHTML = "Loading";
  61269. this._loadingDiv.appendChild(this._loadingTextDiv);
  61270. //set the predefined text
  61271. this._loadingTextDiv.innerHTML = this._loadingText;
  61272. // Generating keyframes
  61273. var style = document.createElement('style');
  61274. style.type = 'text/css';
  61275. 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 }";
  61276. style.innerHTML = keyFrames;
  61277. document.getElementsByTagName('head')[0].appendChild(style);
  61278. // Loading img
  61279. var imgBack = new Image();
  61280. 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";
  61281. imgBack.style.position = "absolute";
  61282. imgBack.style.left = "50%";
  61283. imgBack.style.top = "50%";
  61284. imgBack.style.marginLeft = "-60px";
  61285. imgBack.style.marginTop = "-60px";
  61286. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  61287. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  61288. imgBack.style.transformOrigin = "50% 50%";
  61289. imgBack.style.webkitTransformOrigin = "50% 50%";
  61290. this._loadingDiv.appendChild(imgBack);
  61291. this._resizeLoadingUI();
  61292. window.addEventListener("resize", this._resizeLoadingUI);
  61293. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61294. document.body.appendChild(this._loadingDiv);
  61295. this._loadingDiv.style.opacity = "1";
  61296. };
  61297. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  61298. var _this = this;
  61299. if (!this._loadingDiv) {
  61300. return;
  61301. }
  61302. var onTransitionEnd = function () {
  61303. if (!_this._loadingDiv) {
  61304. return;
  61305. }
  61306. document.body.removeChild(_this._loadingDiv);
  61307. window.removeEventListener("resize", _this._resizeLoadingUI);
  61308. _this._loadingDiv = null;
  61309. };
  61310. this._loadingDiv.style.opacity = "0";
  61311. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  61312. };
  61313. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  61314. set: function (text) {
  61315. this._loadingText = text;
  61316. if (this._loadingTextDiv) {
  61317. this._loadingTextDiv.innerHTML = this._loadingText;
  61318. }
  61319. },
  61320. enumerable: true,
  61321. configurable: true
  61322. });
  61323. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  61324. get: function () {
  61325. return this._loadingDivBackgroundColor;
  61326. },
  61327. set: function (color) {
  61328. this._loadingDivBackgroundColor = color;
  61329. if (!this._loadingDiv) {
  61330. return;
  61331. }
  61332. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61333. },
  61334. enumerable: true,
  61335. configurable: true
  61336. });
  61337. return DefaultLoadingScreen;
  61338. }());
  61339. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  61340. })(BABYLON || (BABYLON = {}));
  61341. //# sourceMappingURL=babylon.loadingScreen.js.map
  61342. var BABYLON;
  61343. (function (BABYLON) {
  61344. var SceneLoaderProgressEvent = /** @class */ (function () {
  61345. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  61346. this.lengthComputable = lengthComputable;
  61347. this.loaded = loaded;
  61348. this.total = total;
  61349. }
  61350. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  61351. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  61352. };
  61353. return SceneLoaderProgressEvent;
  61354. }());
  61355. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  61356. var SceneLoader = /** @class */ (function () {
  61357. function SceneLoader() {
  61358. }
  61359. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  61360. get: function () {
  61361. return 0;
  61362. },
  61363. enumerable: true,
  61364. configurable: true
  61365. });
  61366. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  61367. get: function () {
  61368. return 1;
  61369. },
  61370. enumerable: true,
  61371. configurable: true
  61372. });
  61373. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  61374. get: function () {
  61375. return 2;
  61376. },
  61377. enumerable: true,
  61378. configurable: true
  61379. });
  61380. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  61381. get: function () {
  61382. return 3;
  61383. },
  61384. enumerable: true,
  61385. configurable: true
  61386. });
  61387. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  61388. get: function () {
  61389. return SceneLoader._ForceFullSceneLoadingForIncremental;
  61390. },
  61391. set: function (value) {
  61392. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  61393. },
  61394. enumerable: true,
  61395. configurable: true
  61396. });
  61397. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  61398. get: function () {
  61399. return SceneLoader._ShowLoadingScreen;
  61400. },
  61401. set: function (value) {
  61402. SceneLoader._ShowLoadingScreen = value;
  61403. },
  61404. enumerable: true,
  61405. configurable: true
  61406. });
  61407. Object.defineProperty(SceneLoader, "loggingLevel", {
  61408. get: function () {
  61409. return SceneLoader._loggingLevel;
  61410. },
  61411. set: function (value) {
  61412. SceneLoader._loggingLevel = value;
  61413. },
  61414. enumerable: true,
  61415. configurable: true
  61416. });
  61417. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  61418. get: function () {
  61419. return SceneLoader._CleanBoneMatrixWeights;
  61420. },
  61421. set: function (value) {
  61422. SceneLoader._CleanBoneMatrixWeights = value;
  61423. },
  61424. enumerable: true,
  61425. configurable: true
  61426. });
  61427. SceneLoader._getDefaultPlugin = function () {
  61428. return SceneLoader._registeredPlugins[".babylon"];
  61429. };
  61430. SceneLoader._getPluginForExtension = function (extension) {
  61431. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  61432. if (registeredPlugin) {
  61433. return registeredPlugin;
  61434. }
  61435. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  61436. return SceneLoader._getDefaultPlugin();
  61437. };
  61438. SceneLoader._getPluginForDirectLoad = function (data) {
  61439. for (var extension in SceneLoader._registeredPlugins) {
  61440. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  61441. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  61442. return SceneLoader._registeredPlugins[extension];
  61443. }
  61444. }
  61445. return SceneLoader._getDefaultPlugin();
  61446. };
  61447. SceneLoader._getPluginForFilename = function (sceneFilename) {
  61448. if (sceneFilename.name) {
  61449. sceneFilename = sceneFilename.name;
  61450. }
  61451. var queryStringPosition = sceneFilename.indexOf("?");
  61452. if (queryStringPosition !== -1) {
  61453. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  61454. }
  61455. var dotPosition = sceneFilename.lastIndexOf(".");
  61456. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  61457. return SceneLoader._getPluginForExtension(extension);
  61458. };
  61459. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  61460. SceneLoader._getDirectLoad = function (sceneFilename) {
  61461. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  61462. return sceneFilename.substr(5);
  61463. }
  61464. return null;
  61465. };
  61466. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  61467. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  61468. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  61469. var plugin;
  61470. if (registeredPlugin.plugin.createPlugin) {
  61471. plugin = registeredPlugin.plugin.createPlugin();
  61472. }
  61473. else {
  61474. plugin = registeredPlugin.plugin;
  61475. }
  61476. var useArrayBuffer = registeredPlugin.isBinary;
  61477. var database;
  61478. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  61479. var dataCallback = function (data, responseURL) {
  61480. if (scene.isDisposed) {
  61481. onError("Scene has been disposed");
  61482. return;
  61483. }
  61484. scene.database = database;
  61485. onSuccess(plugin, data, responseURL);
  61486. };
  61487. var request = null;
  61488. var pluginDisposed = false;
  61489. var onDisposeObservable = plugin.onDisposeObservable;
  61490. if (onDisposeObservable) {
  61491. onDisposeObservable.add(function () {
  61492. pluginDisposed = true;
  61493. if (request) {
  61494. request.abort();
  61495. request = null;
  61496. }
  61497. onDispose();
  61498. });
  61499. }
  61500. var manifestChecked = function () {
  61501. if (pluginDisposed) {
  61502. return;
  61503. }
  61504. var url = rootUrl + sceneFilename;
  61505. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  61506. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  61507. } : undefined, database, useArrayBuffer, function (request, exception) {
  61508. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  61509. });
  61510. };
  61511. if (directLoad) {
  61512. dataCallback(directLoad);
  61513. return plugin;
  61514. }
  61515. if (rootUrl.indexOf("file:") === -1) {
  61516. if (scene.getEngine().enableOfflineSupport) {
  61517. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  61518. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  61519. }
  61520. else {
  61521. manifestChecked();
  61522. }
  61523. }
  61524. else {
  61525. var fileOrString = sceneFilename;
  61526. if (fileOrString.name) {
  61527. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  61528. }
  61529. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  61530. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  61531. }
  61532. else {
  61533. onError("Unable to find file named " + sceneFilename);
  61534. }
  61535. }
  61536. return plugin;
  61537. };
  61538. // Public functions
  61539. SceneLoader.GetPluginForExtension = function (extension) {
  61540. return SceneLoader._getPluginForExtension(extension).plugin;
  61541. };
  61542. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  61543. return !!SceneLoader._registeredPlugins[extension];
  61544. };
  61545. SceneLoader.RegisterPlugin = function (plugin) {
  61546. if (typeof plugin.extensions === "string") {
  61547. var extension = plugin.extensions;
  61548. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61549. plugin: plugin,
  61550. isBinary: false
  61551. };
  61552. }
  61553. else {
  61554. var extensions = plugin.extensions;
  61555. Object.keys(extensions).forEach(function (extension) {
  61556. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61557. plugin: plugin,
  61558. isBinary: extensions[extension].isBinary
  61559. };
  61560. });
  61561. }
  61562. };
  61563. /**
  61564. * Import meshes into a scene
  61565. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61566. * @param rootUrl a string that defines the root url for scene and resources
  61567. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61568. * @param scene the instance of BABYLON.Scene to append to
  61569. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  61570. * @param onProgress a callback with a progress event for each file being loaded
  61571. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61572. * @param pluginExtension the extension used to determine the plugin
  61573. * @returns The loaded plugin
  61574. */
  61575. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61576. if (onSuccess === void 0) { onSuccess = null; }
  61577. if (onProgress === void 0) { onProgress = null; }
  61578. if (onError === void 0) { onError = null; }
  61579. if (pluginExtension === void 0) { pluginExtension = null; }
  61580. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61581. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61582. return null;
  61583. }
  61584. var loadingToken = {};
  61585. scene._addPendingData(loadingToken);
  61586. var disposeHandler = function () {
  61587. scene._removePendingData(loadingToken);
  61588. };
  61589. var errorHandler = function (message, exception) {
  61590. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  61591. if (onError) {
  61592. onError(scene, errorMessage, exception);
  61593. }
  61594. else {
  61595. BABYLON.Tools.Error(errorMessage);
  61596. // should the exception be thrown?
  61597. }
  61598. disposeHandler();
  61599. };
  61600. var progressHandler = onProgress ? function (event) {
  61601. try {
  61602. onProgress(event);
  61603. }
  61604. catch (e) {
  61605. errorHandler("Error in onProgress callback", e);
  61606. }
  61607. } : undefined;
  61608. var successHandler = function (meshes, particleSystems, skeletons) {
  61609. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  61610. if (onSuccess) {
  61611. try {
  61612. onSuccess(meshes, particleSystems, skeletons);
  61613. }
  61614. catch (e) {
  61615. errorHandler("Error in onSuccess callback", e);
  61616. }
  61617. }
  61618. scene._removePendingData(loadingToken);
  61619. };
  61620. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61621. if (plugin.rewriteRootURL) {
  61622. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  61623. }
  61624. if (sceneFilename === "") {
  61625. if (sceneFilename === "") {
  61626. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61627. }
  61628. }
  61629. if (plugin.importMesh) {
  61630. var syncedPlugin = plugin;
  61631. var meshes = new Array();
  61632. var particleSystems = new Array();
  61633. var skeletons = new Array();
  61634. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  61635. return;
  61636. }
  61637. scene.loadingPluginName = plugin.name;
  61638. successHandler(meshes, particleSystems, skeletons);
  61639. }
  61640. else {
  61641. var asyncedPlugin = plugin;
  61642. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  61643. scene.loadingPluginName = plugin.name;
  61644. successHandler(result.meshes, result.particleSystems, result.skeletons);
  61645. }).catch(function (error) {
  61646. errorHandler(error.message, error);
  61647. });
  61648. }
  61649. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61650. };
  61651. /**
  61652. * Import meshes into a scene
  61653. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61654. * @param rootUrl a string that defines the root url for scene and resources
  61655. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61656. * @param scene the instance of BABYLON.Scene to append to
  61657. * @param onProgress a callback with a progress event for each file being loaded
  61658. * @param pluginExtension the extension used to determine the plugin
  61659. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  61660. */
  61661. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61662. if (onProgress === void 0) { onProgress = null; }
  61663. if (pluginExtension === void 0) { pluginExtension = null; }
  61664. return new Promise(function (resolve, reject) {
  61665. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61666. resolve({
  61667. meshes: meshes,
  61668. particleSystems: particleSystems,
  61669. skeletons: skeletons
  61670. });
  61671. }, onProgress, function (scene, message, exception) {
  61672. reject(exception || new Error(message));
  61673. });
  61674. });
  61675. };
  61676. /**
  61677. * Load a scene
  61678. * @param rootUrl a string that defines the root url for scene and resources
  61679. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61680. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61681. * @param onSuccess a callback with the scene when import succeeds
  61682. * @param onProgress a callback with a progress event for each file being loaded
  61683. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61684. * @param pluginExtension the extension used to determine the plugin
  61685. * @returns The loaded plugin
  61686. */
  61687. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61688. if (onSuccess === void 0) { onSuccess = null; }
  61689. if (onProgress === void 0) { onProgress = null; }
  61690. if (onError === void 0) { onError = null; }
  61691. if (pluginExtension === void 0) { pluginExtension = null; }
  61692. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61693. };
  61694. /**
  61695. * Load a scene
  61696. * @param rootUrl a string that defines the root url for scene and resources
  61697. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61698. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61699. * @param onProgress a callback with a progress event for each file being loaded
  61700. * @param pluginExtension the extension used to determine the plugin
  61701. * @returns The loaded scene
  61702. */
  61703. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61704. if (onProgress === void 0) { onProgress = null; }
  61705. if (pluginExtension === void 0) { pluginExtension = null; }
  61706. return new Promise(function (resolve, reject) {
  61707. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61708. resolve(scene);
  61709. }, onProgress, function (scene, message, exception) {
  61710. reject(exception || new Error(message));
  61711. }, pluginExtension);
  61712. });
  61713. };
  61714. /**
  61715. * Append a scene
  61716. * @param rootUrl a string that defines the root url for scene and resources
  61717. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61718. * @param scene is the instance of BABYLON.Scene to append to
  61719. * @param onSuccess a callback with the scene when import succeeds
  61720. * @param onProgress a callback with a progress event for each file being loaded
  61721. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61722. * @param pluginExtension the extension used to determine the plugin
  61723. * @returns The loaded plugin
  61724. */
  61725. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61726. if (onSuccess === void 0) { onSuccess = null; }
  61727. if (onProgress === void 0) { onProgress = null; }
  61728. if (onError === void 0) { onError = null; }
  61729. if (pluginExtension === void 0) { pluginExtension = null; }
  61730. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61731. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61732. return null;
  61733. }
  61734. if (SceneLoader.ShowLoadingScreen) {
  61735. scene.getEngine().displayLoadingUI();
  61736. }
  61737. var loadingToken = {};
  61738. scene._addPendingData(loadingToken);
  61739. var disposeHandler = function () {
  61740. scene._removePendingData(loadingToken);
  61741. scene.getEngine().hideLoadingUI();
  61742. };
  61743. var errorHandler = function (message, exception) {
  61744. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61745. if (onError) {
  61746. onError(scene, errorMessage, exception);
  61747. }
  61748. else {
  61749. BABYLON.Tools.Error(errorMessage);
  61750. // should the exception be thrown?
  61751. }
  61752. disposeHandler();
  61753. };
  61754. var progressHandler = onProgress ? function (event) {
  61755. try {
  61756. onProgress(event);
  61757. }
  61758. catch (e) {
  61759. errorHandler("Error in onProgress callback", e);
  61760. }
  61761. } : undefined;
  61762. var successHandler = function () {
  61763. if (onSuccess) {
  61764. try {
  61765. onSuccess(scene);
  61766. }
  61767. catch (e) {
  61768. errorHandler("Error in onSuccess callback", e);
  61769. }
  61770. }
  61771. scene._removePendingData(loadingToken);
  61772. };
  61773. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61774. if (sceneFilename === "") {
  61775. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61776. }
  61777. if (plugin.load) {
  61778. var syncedPlugin = plugin;
  61779. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61780. return;
  61781. }
  61782. scene.loadingPluginName = plugin.name;
  61783. successHandler();
  61784. }
  61785. else {
  61786. var asyncedPlugin = plugin;
  61787. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61788. scene.loadingPluginName = plugin.name;
  61789. successHandler();
  61790. }).catch(function (error) {
  61791. errorHandler(error.message, error);
  61792. });
  61793. }
  61794. if (SceneLoader.ShowLoadingScreen) {
  61795. scene.executeWhenReady(function () {
  61796. scene.getEngine().hideLoadingUI();
  61797. });
  61798. }
  61799. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61800. };
  61801. /**
  61802. * Append a scene
  61803. * @param rootUrl a string that defines the root url for scene and resources
  61804. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61805. * @param scene is the instance of BABYLON.Scene to append to
  61806. * @param onProgress a callback with a progress event for each file being loaded
  61807. * @param pluginExtension the extension used to determine the plugin
  61808. * @returns The given scene
  61809. */
  61810. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61811. if (onProgress === void 0) { onProgress = null; }
  61812. if (pluginExtension === void 0) { pluginExtension = null; }
  61813. return new Promise(function (resolve, reject) {
  61814. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  61815. resolve(scene);
  61816. }, onProgress, function (scene, message, exception) {
  61817. reject(exception || new Error(message));
  61818. }, pluginExtension);
  61819. });
  61820. };
  61821. /**
  61822. * Load a scene into an asset container
  61823. * @param rootUrl a string that defines the root url for scene and resources
  61824. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61825. * @param scene is the instance of BABYLON.Scene to append to
  61826. * @param onSuccess a callback with the scene when import succeeds
  61827. * @param onProgress a callback with a progress event for each file being loaded
  61828. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61829. * @param pluginExtension the extension used to determine the plugin
  61830. * @returns The loaded plugin
  61831. */
  61832. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61833. if (onSuccess === void 0) { onSuccess = null; }
  61834. if (onProgress === void 0) { onProgress = null; }
  61835. if (onError === void 0) { onError = null; }
  61836. if (pluginExtension === void 0) { pluginExtension = null; }
  61837. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61838. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61839. return null;
  61840. }
  61841. var loadingToken = {};
  61842. scene._addPendingData(loadingToken);
  61843. var disposeHandler = function () {
  61844. scene._removePendingData(loadingToken);
  61845. };
  61846. var errorHandler = function (message, exception) {
  61847. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61848. if (onError) {
  61849. onError(scene, errorMessage, exception);
  61850. }
  61851. else {
  61852. BABYLON.Tools.Error(errorMessage);
  61853. // should the exception be thrown?
  61854. }
  61855. disposeHandler();
  61856. };
  61857. var progressHandler = onProgress ? function (event) {
  61858. try {
  61859. onProgress(event);
  61860. }
  61861. catch (e) {
  61862. errorHandler("Error in onProgress callback", e);
  61863. }
  61864. } : undefined;
  61865. var successHandler = function (assets) {
  61866. if (onSuccess) {
  61867. try {
  61868. onSuccess(assets);
  61869. }
  61870. catch (e) {
  61871. errorHandler("Error in onSuccess callback", e);
  61872. }
  61873. }
  61874. scene._removePendingData(loadingToken);
  61875. };
  61876. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61877. if (plugin.loadAssetContainer) {
  61878. var syncedPlugin = plugin;
  61879. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  61880. if (!assetContainer) {
  61881. return;
  61882. }
  61883. scene.loadingPluginName = plugin.name;
  61884. successHandler(assetContainer);
  61885. }
  61886. else if (plugin.loadAssetContainerAsync) {
  61887. var asyncedPlugin = plugin;
  61888. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  61889. scene.loadingPluginName = plugin.name;
  61890. successHandler(assetContainer);
  61891. }).catch(function (error) {
  61892. errorHandler(error.message, error);
  61893. });
  61894. }
  61895. else {
  61896. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61897. }
  61898. if (SceneLoader.ShowLoadingScreen) {
  61899. scene.executeWhenReady(function () {
  61900. scene.getEngine().hideLoadingUI();
  61901. });
  61902. }
  61903. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61904. };
  61905. /**
  61906. * Load a scene into an asset container
  61907. * @param rootUrl a string that defines the root url for scene and resources
  61908. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61909. * @param scene is the instance of BABYLON.Scene to append to
  61910. * @param onProgress a callback with a progress event for each file being loaded
  61911. * @param pluginExtension the extension used to determine the plugin
  61912. * @returns The loaded asset container
  61913. */
  61914. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61915. if (onProgress === void 0) { onProgress = null; }
  61916. if (pluginExtension === void 0) { pluginExtension = null; }
  61917. return new Promise(function (resolve, reject) {
  61918. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61919. resolve(assetContainer);
  61920. }, onProgress, function (scene, message, exception) {
  61921. reject(exception || new Error(message));
  61922. }, pluginExtension);
  61923. });
  61924. };
  61925. // Flags
  61926. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61927. SceneLoader._ShowLoadingScreen = true;
  61928. SceneLoader._CleanBoneMatrixWeights = false;
  61929. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61930. // Members
  61931. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61932. SceneLoader._registeredPlugins = {};
  61933. return SceneLoader;
  61934. }());
  61935. BABYLON.SceneLoader = SceneLoader;
  61936. ;
  61937. })(BABYLON || (BABYLON = {}));
  61938. //# sourceMappingURL=babylon.sceneLoader.js.map
  61939. var BABYLON;
  61940. (function (BABYLON) {
  61941. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61942. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61943. var parsedMaterial = parsedData.materials[index];
  61944. if (parsedMaterial.id === id) {
  61945. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61946. }
  61947. }
  61948. return null;
  61949. };
  61950. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61951. for (var i in names) {
  61952. if (mesh.name === names[i]) {
  61953. hierarchyIds.push(mesh.id);
  61954. return true;
  61955. }
  61956. }
  61957. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61958. hierarchyIds.push(mesh.id);
  61959. return true;
  61960. }
  61961. return false;
  61962. };
  61963. var logOperation = function (operation, producer) {
  61964. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61965. };
  61966. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61967. if (addToScene === void 0) { addToScene = false; }
  61968. var container = new BABYLON.AssetContainer(scene);
  61969. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61970. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61971. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61972. // and avoid problems with multiple concurrent .babylon loads.
  61973. var log = "importScene has failed JSON parse";
  61974. try {
  61975. var parsedData = JSON.parse(data);
  61976. log = "";
  61977. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61978. var index;
  61979. var cache;
  61980. // Lights
  61981. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61982. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61983. var parsedLight = parsedData.lights[index];
  61984. var light = BABYLON.Light.Parse(parsedLight, scene);
  61985. if (light) {
  61986. container.lights.push(light);
  61987. log += (index === 0 ? "\n\tLights:" : "");
  61988. log += "\n\t\t" + light.toString(fullDetails);
  61989. }
  61990. }
  61991. }
  61992. // Animations
  61993. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61994. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61995. var parsedAnimation = parsedData.animations[index];
  61996. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61997. scene.animations.push(animation);
  61998. container.animations.push(animation);
  61999. log += (index === 0 ? "\n\tAnimations:" : "");
  62000. log += "\n\t\t" + animation.toString(fullDetails);
  62001. }
  62002. }
  62003. // Materials
  62004. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  62005. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62006. var parsedMaterial = parsedData.materials[index];
  62007. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62008. container.materials.push(mat);
  62009. log += (index === 0 ? "\n\tMaterials:" : "");
  62010. log += "\n\t\t" + mat.toString(fullDetails);
  62011. }
  62012. }
  62013. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62014. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  62015. var parsedMultiMaterial = parsedData.multiMaterials[index];
  62016. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62017. container.multiMaterials.push(mmat);
  62018. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  62019. log += "\n\t\t" + mmat.toString(fullDetails);
  62020. }
  62021. }
  62022. // Morph targets
  62023. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  62024. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  62025. var managerData = _a[_i];
  62026. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  62027. }
  62028. }
  62029. // Skeletons
  62030. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62031. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  62032. var parsedSkeleton = parsedData.skeletons[index];
  62033. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62034. container.skeletons.push(skeleton);
  62035. log += (index === 0 ? "\n\tSkeletons:" : "");
  62036. log += "\n\t\t" + skeleton.toString(fullDetails);
  62037. }
  62038. }
  62039. // Geometries
  62040. var geometries = parsedData.geometries;
  62041. if (geometries !== undefined && geometries !== null) {
  62042. var addedGeometry = new Array();
  62043. // Boxes
  62044. var boxes = geometries.boxes;
  62045. if (boxes !== undefined && boxes !== null) {
  62046. for (index = 0, cache = boxes.length; index < cache; index++) {
  62047. var parsedBox = boxes[index];
  62048. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  62049. }
  62050. }
  62051. // Spheres
  62052. var spheres = geometries.spheres;
  62053. if (spheres !== undefined && spheres !== null) {
  62054. for (index = 0, cache = spheres.length; index < cache; index++) {
  62055. var parsedSphere = spheres[index];
  62056. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  62057. }
  62058. }
  62059. // Cylinders
  62060. var cylinders = geometries.cylinders;
  62061. if (cylinders !== undefined && cylinders !== null) {
  62062. for (index = 0, cache = cylinders.length; index < cache; index++) {
  62063. var parsedCylinder = cylinders[index];
  62064. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  62065. }
  62066. }
  62067. // Toruses
  62068. var toruses = geometries.toruses;
  62069. if (toruses !== undefined && toruses !== null) {
  62070. for (index = 0, cache = toruses.length; index < cache; index++) {
  62071. var parsedTorus = toruses[index];
  62072. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  62073. }
  62074. }
  62075. // Grounds
  62076. var grounds = geometries.grounds;
  62077. if (grounds !== undefined && grounds !== null) {
  62078. for (index = 0, cache = grounds.length; index < cache; index++) {
  62079. var parsedGround = grounds[index];
  62080. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  62081. }
  62082. }
  62083. // Planes
  62084. var planes = geometries.planes;
  62085. if (planes !== undefined && planes !== null) {
  62086. for (index = 0, cache = planes.length; index < cache; index++) {
  62087. var parsedPlane = planes[index];
  62088. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  62089. }
  62090. }
  62091. // TorusKnots
  62092. var torusKnots = geometries.torusKnots;
  62093. if (torusKnots !== undefined && torusKnots !== null) {
  62094. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  62095. var parsedTorusKnot = torusKnots[index];
  62096. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  62097. }
  62098. }
  62099. // VertexData
  62100. var vertexData = geometries.vertexData;
  62101. if (vertexData !== undefined && vertexData !== null) {
  62102. for (index = 0, cache = vertexData.length; index < cache; index++) {
  62103. var parsedVertexData = vertexData[index];
  62104. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  62105. }
  62106. }
  62107. addedGeometry.forEach(function (g) {
  62108. if (g) {
  62109. container.geometries.push(g);
  62110. }
  62111. });
  62112. }
  62113. // Transform nodes
  62114. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  62115. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  62116. var parsedTransformNode = parsedData.transformNodes[index];
  62117. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  62118. container.transformNodes.push(node);
  62119. }
  62120. }
  62121. // Meshes
  62122. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62123. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62124. var parsedMesh = parsedData.meshes[index];
  62125. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62126. container.meshes.push(mesh);
  62127. log += (index === 0 ? "\n\tMeshes:" : "");
  62128. log += "\n\t\t" + mesh.toString(fullDetails);
  62129. }
  62130. }
  62131. // Cameras
  62132. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  62133. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  62134. var parsedCamera = parsedData.cameras[index];
  62135. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  62136. container.cameras.push(camera);
  62137. log += (index === 0 ? "\n\tCameras:" : "");
  62138. log += "\n\t\t" + camera.toString(fullDetails);
  62139. }
  62140. }
  62141. // Browsing all the graph to connect the dots
  62142. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  62143. var camera = scene.cameras[index];
  62144. if (camera._waitingParentId) {
  62145. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  62146. camera._waitingParentId = null;
  62147. }
  62148. }
  62149. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62150. var light_1 = scene.lights[index];
  62151. if (light_1 && light_1._waitingParentId) {
  62152. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  62153. light_1._waitingParentId = null;
  62154. }
  62155. }
  62156. // Sounds
  62157. // TODO: add sound
  62158. var loadedSounds = [];
  62159. var loadedSound;
  62160. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  62161. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  62162. var parsedSound = parsedData.sounds[index];
  62163. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62164. if (!parsedSound.url)
  62165. parsedSound.url = parsedSound.name;
  62166. if (!loadedSounds[parsedSound.url]) {
  62167. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  62168. loadedSounds[parsedSound.url] = loadedSound;
  62169. container.sounds.push(loadedSound);
  62170. }
  62171. else {
  62172. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  62173. }
  62174. }
  62175. else {
  62176. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  62177. }
  62178. }
  62179. }
  62180. loadedSounds = [];
  62181. // Connect parents & children and parse actions
  62182. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  62183. var transformNode = scene.transformNodes[index];
  62184. if (transformNode._waitingParentId) {
  62185. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  62186. transformNode._waitingParentId = null;
  62187. }
  62188. }
  62189. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62190. var mesh = scene.meshes[index];
  62191. if (mesh._waitingParentId) {
  62192. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  62193. mesh._waitingParentId = null;
  62194. }
  62195. if (mesh._waitingActions) {
  62196. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  62197. mesh._waitingActions = null;
  62198. }
  62199. }
  62200. // freeze world matrix application
  62201. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62202. var currentMesh = scene.meshes[index];
  62203. if (currentMesh._waitingFreezeWorldMatrix) {
  62204. currentMesh.freezeWorldMatrix();
  62205. currentMesh._waitingFreezeWorldMatrix = null;
  62206. }
  62207. else {
  62208. currentMesh.computeWorldMatrix(true);
  62209. }
  62210. }
  62211. // Particles Systems
  62212. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62213. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62214. var parsedParticleSystem = parsedData.particleSystems[index];
  62215. if (parsedParticleSystem.activeParticleCount) {
  62216. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62217. container.particleSystems.push(ps);
  62218. }
  62219. else {
  62220. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62221. container.particleSystems.push(ps);
  62222. }
  62223. }
  62224. }
  62225. // Lens flares
  62226. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  62227. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  62228. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  62229. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  62230. container.lensFlareSystems.push(lf);
  62231. }
  62232. }
  62233. // Shadows
  62234. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  62235. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  62236. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  62237. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  62238. container.shadowGenerators.push(sg);
  62239. }
  62240. }
  62241. // Lights exclusions / inclusions
  62242. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62243. var light_2 = scene.lights[index];
  62244. // Excluded check
  62245. if (light_2._excludedMeshesIds.length > 0) {
  62246. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  62247. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  62248. if (excludedMesh) {
  62249. light_2.excludedMeshes.push(excludedMesh);
  62250. }
  62251. }
  62252. light_2._excludedMeshesIds = [];
  62253. }
  62254. // Included check
  62255. if (light_2._includedOnlyMeshesIds.length > 0) {
  62256. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  62257. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  62258. if (includedOnlyMesh) {
  62259. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  62260. }
  62261. }
  62262. light_2._includedOnlyMeshesIds = [];
  62263. }
  62264. }
  62265. // Actions (scene)
  62266. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  62267. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  62268. }
  62269. if (!addToScene) {
  62270. container.removeAllFromScene();
  62271. }
  62272. }
  62273. catch (err) {
  62274. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  62275. if (onError) {
  62276. onError(msg, err);
  62277. }
  62278. else {
  62279. BABYLON.Tools.Log(msg);
  62280. throw err;
  62281. }
  62282. }
  62283. finally {
  62284. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62285. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62286. }
  62287. }
  62288. return container;
  62289. };
  62290. BABYLON.SceneLoader.RegisterPlugin({
  62291. name: "babylon.js",
  62292. extensions: ".babylon",
  62293. canDirectLoad: function (data) {
  62294. if (data.indexOf("babylon") !== -1) {
  62295. return true;
  62296. }
  62297. return false;
  62298. },
  62299. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  62300. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62301. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62302. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62303. // and avoid problems with multiple concurrent .babylon loads.
  62304. var log = "importMesh has failed JSON parse";
  62305. try {
  62306. var parsedData = JSON.parse(data);
  62307. log = "";
  62308. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62309. if (!meshesNames) {
  62310. meshesNames = null;
  62311. }
  62312. else if (!Array.isArray(meshesNames)) {
  62313. meshesNames = [meshesNames];
  62314. }
  62315. var hierarchyIds = new Array();
  62316. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62317. var loadedSkeletonsIds = [];
  62318. var loadedMaterialsIds = [];
  62319. var index;
  62320. var cache;
  62321. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62322. var parsedMesh = parsedData.meshes[index];
  62323. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  62324. if (meshesNames !== null) {
  62325. // Remove found mesh name from list.
  62326. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  62327. }
  62328. //Geometry?
  62329. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  62330. //does the file contain geometries?
  62331. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  62332. //find the correct geometry and add it to the scene
  62333. var found = false;
  62334. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  62335. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  62336. return;
  62337. }
  62338. else {
  62339. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  62340. if (parsedGeometryData.id === parsedMesh.geometryId) {
  62341. switch (geometryType) {
  62342. case "boxes":
  62343. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  62344. break;
  62345. case "spheres":
  62346. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  62347. break;
  62348. case "cylinders":
  62349. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  62350. break;
  62351. case "toruses":
  62352. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  62353. break;
  62354. case "grounds":
  62355. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  62356. break;
  62357. case "planes":
  62358. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  62359. break;
  62360. case "torusKnots":
  62361. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  62362. break;
  62363. case "vertexData":
  62364. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  62365. break;
  62366. }
  62367. found = true;
  62368. }
  62369. });
  62370. }
  62371. });
  62372. if (found === false) {
  62373. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  62374. }
  62375. }
  62376. }
  62377. // Material ?
  62378. if (parsedMesh.materialId) {
  62379. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  62380. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62381. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  62382. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  62383. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  62384. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  62385. var subMatId = parsedMultiMaterial.materials[matIndex];
  62386. loadedMaterialsIds.push(subMatId);
  62387. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  62388. if (mat) {
  62389. log += "\n\tMaterial " + mat.toString(fullDetails);
  62390. }
  62391. }
  62392. loadedMaterialsIds.push(parsedMultiMaterial.id);
  62393. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62394. if (mmat) {
  62395. materialFound = true;
  62396. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  62397. }
  62398. break;
  62399. }
  62400. }
  62401. }
  62402. if (materialFound === false) {
  62403. loadedMaterialsIds.push(parsedMesh.materialId);
  62404. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  62405. if (!mat) {
  62406. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  62407. }
  62408. else {
  62409. log += "\n\tMaterial " + mat.toString(fullDetails);
  62410. }
  62411. }
  62412. }
  62413. // Skeleton ?
  62414. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62415. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  62416. if (skeletonAlreadyLoaded === false) {
  62417. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  62418. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  62419. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  62420. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62421. skeletons.push(skeleton);
  62422. loadedSkeletonsIds.push(parsedSkeleton.id);
  62423. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  62424. }
  62425. }
  62426. }
  62427. }
  62428. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62429. meshes.push(mesh);
  62430. log += "\n\tMesh " + mesh.toString(fullDetails);
  62431. }
  62432. }
  62433. // Connecting parents
  62434. var currentMesh;
  62435. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62436. currentMesh = scene.meshes[index];
  62437. if (currentMesh._waitingParentId) {
  62438. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  62439. currentMesh._waitingParentId = null;
  62440. }
  62441. }
  62442. // freeze and compute world matrix application
  62443. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62444. currentMesh = scene.meshes[index];
  62445. if (currentMesh._waitingFreezeWorldMatrix) {
  62446. currentMesh.freezeWorldMatrix();
  62447. currentMesh._waitingFreezeWorldMatrix = null;
  62448. }
  62449. else {
  62450. currentMesh.computeWorldMatrix(true);
  62451. }
  62452. }
  62453. }
  62454. // Particles
  62455. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62456. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62457. var parsedParticleSystem = parsedData.particleSystems[index];
  62458. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  62459. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  62460. }
  62461. }
  62462. }
  62463. return true;
  62464. }
  62465. catch (err) {
  62466. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  62467. if (onError) {
  62468. onError(msg, err);
  62469. }
  62470. else {
  62471. BABYLON.Tools.Log(msg);
  62472. throw err;
  62473. }
  62474. }
  62475. finally {
  62476. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62477. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62478. }
  62479. }
  62480. return false;
  62481. },
  62482. load: function (scene, data, rootUrl, onError) {
  62483. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62484. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62485. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62486. // and avoid problems with multiple concurrent .babylon loads.
  62487. var log = "importScene has failed JSON parse";
  62488. try {
  62489. var parsedData = JSON.parse(data);
  62490. log = "";
  62491. // Scene
  62492. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  62493. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  62494. }
  62495. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  62496. scene.autoClear = parsedData.autoClear;
  62497. }
  62498. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  62499. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  62500. }
  62501. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  62502. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  62503. }
  62504. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  62505. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  62506. }
  62507. // Fog
  62508. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  62509. scene.fogMode = parsedData.fogMode;
  62510. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  62511. scene.fogStart = parsedData.fogStart;
  62512. scene.fogEnd = parsedData.fogEnd;
  62513. scene.fogDensity = parsedData.fogDensity;
  62514. log += "\tFog mode for scene: ";
  62515. switch (scene.fogMode) {
  62516. // getters not compiling, so using hardcoded
  62517. case 1:
  62518. log += "exp\n";
  62519. break;
  62520. case 2:
  62521. log += "exp2\n";
  62522. break;
  62523. case 3:
  62524. log += "linear\n";
  62525. break;
  62526. }
  62527. }
  62528. //Physics
  62529. if (parsedData.physicsEnabled) {
  62530. var physicsPlugin;
  62531. if (parsedData.physicsEngine === "cannon") {
  62532. physicsPlugin = new BABYLON.CannonJSPlugin();
  62533. }
  62534. else if (parsedData.physicsEngine === "oimo") {
  62535. physicsPlugin = new BABYLON.OimoJSPlugin();
  62536. }
  62537. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  62538. //else - default engine, which is currently oimo
  62539. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  62540. scene.enablePhysics(physicsGravity, physicsPlugin);
  62541. }
  62542. // Metadata
  62543. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  62544. scene.metadata = parsedData.metadata;
  62545. }
  62546. //collisions, if defined. otherwise, default is true
  62547. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  62548. scene.collisionsEnabled = parsedData.collisionsEnabled;
  62549. }
  62550. scene.workerCollisions = !!parsedData.workerCollisions;
  62551. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  62552. if (!container) {
  62553. return false;
  62554. }
  62555. if (parsedData.autoAnimate) {
  62556. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  62557. }
  62558. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  62559. scene.setActiveCameraByID(parsedData.activeCameraID);
  62560. }
  62561. // Environment texture
  62562. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  62563. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  62564. if (parsedData.createDefaultSkybox === true) {
  62565. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  62566. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  62567. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  62568. }
  62569. }
  62570. // Finish
  62571. return true;
  62572. }
  62573. catch (err) {
  62574. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  62575. if (onError) {
  62576. onError(msg, err);
  62577. }
  62578. else {
  62579. BABYLON.Tools.Log(msg);
  62580. throw err;
  62581. }
  62582. }
  62583. finally {
  62584. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62585. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62586. }
  62587. }
  62588. return false;
  62589. },
  62590. loadAssetContainer: function (scene, data, rootUrl, onError) {
  62591. var container = loadAssetContainer(scene, data, rootUrl, onError);
  62592. return container;
  62593. }
  62594. });
  62595. })(BABYLON || (BABYLON = {}));
  62596. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  62597. var BABYLON;
  62598. (function (BABYLON) {
  62599. var FilesInput = /** @class */ (function () {
  62600. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  62601. this.onProcessFileCallback = function () { return true; };
  62602. this._engine = engine;
  62603. this._currentScene = scene;
  62604. this._sceneLoadedCallback = sceneLoadedCallback;
  62605. this._progressCallback = progressCallback;
  62606. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  62607. this._textureLoadingCallback = textureLoadingCallback;
  62608. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  62609. this._onReloadCallback = onReloadCallback;
  62610. this._errorCallback = errorCallback;
  62611. }
  62612. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  62613. var _this = this;
  62614. if (elementToMonitor) {
  62615. this._elementToMonitor = elementToMonitor;
  62616. this._dragEnterHandler = function (e) { _this.drag(e); };
  62617. this._dragOverHandler = function (e) { _this.drag(e); };
  62618. this._dropHandler = function (e) { _this.drop(e); };
  62619. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  62620. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  62621. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  62622. }
  62623. };
  62624. FilesInput.prototype.dispose = function () {
  62625. if (!this._elementToMonitor) {
  62626. return;
  62627. }
  62628. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  62629. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  62630. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  62631. };
  62632. FilesInput.prototype.renderFunction = function () {
  62633. if (this._additionalRenderLoopLogicCallback) {
  62634. this._additionalRenderLoopLogicCallback();
  62635. }
  62636. if (this._currentScene) {
  62637. if (this._textureLoadingCallback) {
  62638. var remaining = this._currentScene.getWaitingItemsCount();
  62639. if (remaining > 0) {
  62640. this._textureLoadingCallback(remaining);
  62641. }
  62642. }
  62643. this._currentScene.render();
  62644. }
  62645. };
  62646. FilesInput.prototype.drag = function (e) {
  62647. e.stopPropagation();
  62648. e.preventDefault();
  62649. };
  62650. FilesInput.prototype.drop = function (eventDrop) {
  62651. eventDrop.stopPropagation();
  62652. eventDrop.preventDefault();
  62653. this.loadFiles(eventDrop);
  62654. };
  62655. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  62656. var _this = this;
  62657. var reader = folder.createReader();
  62658. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  62659. reader.readEntries(function (entries) {
  62660. remaining.count += entries.length;
  62661. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  62662. var entry = entries_1[_i];
  62663. if (entry.isFile) {
  62664. entry.file(function (file) {
  62665. file.correctName = relativePath + file.name;
  62666. files.push(file);
  62667. if (--remaining.count === 0) {
  62668. callback();
  62669. }
  62670. });
  62671. }
  62672. else if (entry.isDirectory) {
  62673. _this._traverseFolder(entry, files, remaining, callback);
  62674. }
  62675. }
  62676. if (--remaining.count) {
  62677. callback();
  62678. }
  62679. });
  62680. };
  62681. FilesInput.prototype._processFiles = function (files) {
  62682. for (var i = 0; i < files.length; i++) {
  62683. var name = files[i].correctName.toLowerCase();
  62684. var extension = name.split('.').pop();
  62685. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62686. continue;
  62687. }
  62688. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62689. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62690. this._sceneFileToLoad = files[i];
  62691. }
  62692. else {
  62693. FilesInput.FilesToLoad[name] = files[i];
  62694. }
  62695. }
  62696. };
  62697. FilesInput.prototype.loadFiles = function (event) {
  62698. var _this = this;
  62699. if (this._startingProcessingFilesCallback)
  62700. this._startingProcessingFilesCallback();
  62701. // Handling data transfer via drag'n'drop
  62702. if (event && event.dataTransfer && event.dataTransfer.files) {
  62703. this._filesToLoad = event.dataTransfer.files;
  62704. }
  62705. // Handling files from input files
  62706. if (event && event.target && event.target.files) {
  62707. this._filesToLoad = event.target.files;
  62708. }
  62709. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62710. var files_1 = new Array();
  62711. var folders = [];
  62712. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62713. for (var i = 0; i < this._filesToLoad.length; i++) {
  62714. var fileToLoad = this._filesToLoad[i];
  62715. var name_1 = fileToLoad.name.toLowerCase();
  62716. var entry = void 0;
  62717. fileToLoad.correctName = name_1;
  62718. if (items) {
  62719. var item = items[i];
  62720. if (item.getAsEntry) {
  62721. entry = item.getAsEntry();
  62722. }
  62723. else if (item.webkitGetAsEntry) {
  62724. entry = item.webkitGetAsEntry();
  62725. }
  62726. }
  62727. if (!entry) {
  62728. files_1.push(fileToLoad);
  62729. }
  62730. else {
  62731. if (entry.isDirectory) {
  62732. folders.push(entry);
  62733. }
  62734. else {
  62735. files_1.push(fileToLoad);
  62736. }
  62737. }
  62738. }
  62739. if (folders.length === 0) {
  62740. this._processFiles(files_1);
  62741. this._processReload();
  62742. }
  62743. else {
  62744. var remaining = { count: folders.length };
  62745. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62746. var folder = folders_1[_i];
  62747. this._traverseFolder(folder, files_1, remaining, function () {
  62748. _this._processFiles(files_1);
  62749. if (remaining.count === 0) {
  62750. _this._processReload();
  62751. }
  62752. });
  62753. }
  62754. }
  62755. }
  62756. };
  62757. FilesInput.prototype._processReload = function () {
  62758. if (this._onReloadCallback) {
  62759. this._onReloadCallback(this._sceneFileToLoad);
  62760. }
  62761. else {
  62762. this.reload();
  62763. }
  62764. };
  62765. FilesInput.prototype.reload = function () {
  62766. var _this = this;
  62767. // If a scene file has been provided
  62768. if (this._sceneFileToLoad) {
  62769. if (this._currentScene) {
  62770. if (BABYLON.Tools.errorsCount > 0) {
  62771. BABYLON.Tools.ClearLogCache();
  62772. }
  62773. this._engine.stopRenderLoop();
  62774. this._currentScene.dispose();
  62775. }
  62776. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62777. if (_this._progressCallback) {
  62778. _this._progressCallback(progress);
  62779. }
  62780. }).then(function (scene) {
  62781. _this._currentScene = scene;
  62782. if (_this._sceneLoadedCallback) {
  62783. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62784. }
  62785. // Wait for textures and shaders to be ready
  62786. _this._currentScene.executeWhenReady(function () {
  62787. _this._engine.runRenderLoop(function () {
  62788. _this.renderFunction();
  62789. });
  62790. });
  62791. }).catch(function (error) {
  62792. if (_this._errorCallback) {
  62793. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62794. }
  62795. });
  62796. }
  62797. else {
  62798. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  62799. }
  62800. };
  62801. FilesInput.FilesToLoad = {};
  62802. return FilesInput;
  62803. }());
  62804. BABYLON.FilesInput = FilesInput;
  62805. })(BABYLON || (BABYLON = {}));
  62806. //# sourceMappingURL=babylon.filesInput.js.map
  62807. var BABYLON;
  62808. (function (BABYLON) {
  62809. /**
  62810. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62811. * The underlying implementation relies on an associative array to ensure the best performances.
  62812. * The value can be anything including 'null' but except 'undefined'
  62813. */
  62814. var StringDictionary = /** @class */ (function () {
  62815. function StringDictionary() {
  62816. this._count = 0;
  62817. this._data = {};
  62818. }
  62819. /**
  62820. * This will clear this dictionary and copy the content from the 'source' one.
  62821. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62822. * @param source the dictionary to take the content from and copy to this dictionary
  62823. */
  62824. StringDictionary.prototype.copyFrom = function (source) {
  62825. var _this = this;
  62826. this.clear();
  62827. source.forEach(function (t, v) { return _this.add(t, v); });
  62828. };
  62829. /**
  62830. * Get a value based from its key
  62831. * @param key the given key to get the matching value from
  62832. * @return the value if found, otherwise undefined is returned
  62833. */
  62834. StringDictionary.prototype.get = function (key) {
  62835. var val = this._data[key];
  62836. if (val !== undefined) {
  62837. return val;
  62838. }
  62839. return undefined;
  62840. };
  62841. /**
  62842. * Get a value from its key or add it if it doesn't exist.
  62843. * This method will ensure you that a given key/data will be present in the dictionary.
  62844. * @param key the given key to get the matching value from
  62845. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62846. * The factory will only be invoked if there's no data for the given key.
  62847. * @return the value corresponding to the key.
  62848. */
  62849. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62850. var val = this.get(key);
  62851. if (val !== undefined) {
  62852. return val;
  62853. }
  62854. val = factory(key);
  62855. if (val) {
  62856. this.add(key, val);
  62857. }
  62858. return val;
  62859. };
  62860. /**
  62861. * Get a value from its key if present in the dictionary otherwise add it
  62862. * @param key the key to get the value from
  62863. * @param val if there's no such key/value pair in the dictionary add it with this value
  62864. * @return the value corresponding to the key
  62865. */
  62866. StringDictionary.prototype.getOrAdd = function (key, val) {
  62867. var curVal = this.get(key);
  62868. if (curVal !== undefined) {
  62869. return curVal;
  62870. }
  62871. this.add(key, val);
  62872. return val;
  62873. };
  62874. /**
  62875. * Check if there's a given key in the dictionary
  62876. * @param key the key to check for
  62877. * @return true if the key is present, false otherwise
  62878. */
  62879. StringDictionary.prototype.contains = function (key) {
  62880. return this._data[key] !== undefined;
  62881. };
  62882. /**
  62883. * Add a new key and its corresponding value
  62884. * @param key the key to add
  62885. * @param value the value corresponding to the key
  62886. * @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
  62887. */
  62888. StringDictionary.prototype.add = function (key, value) {
  62889. if (this._data[key] !== undefined) {
  62890. return false;
  62891. }
  62892. this._data[key] = value;
  62893. ++this._count;
  62894. return true;
  62895. };
  62896. StringDictionary.prototype.set = function (key, value) {
  62897. if (this._data[key] === undefined) {
  62898. return false;
  62899. }
  62900. this._data[key] = value;
  62901. return true;
  62902. };
  62903. /**
  62904. * Get the element of the given key and remove it from the dictionary
  62905. * @param key
  62906. */
  62907. StringDictionary.prototype.getAndRemove = function (key) {
  62908. var val = this.get(key);
  62909. if (val !== undefined) {
  62910. delete this._data[key];
  62911. --this._count;
  62912. return val;
  62913. }
  62914. return null;
  62915. };
  62916. /**
  62917. * Remove a key/value from the dictionary.
  62918. * @param key the key to remove
  62919. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62920. */
  62921. StringDictionary.prototype.remove = function (key) {
  62922. if (this.contains(key)) {
  62923. delete this._data[key];
  62924. --this._count;
  62925. return true;
  62926. }
  62927. return false;
  62928. };
  62929. /**
  62930. * Clear the whole content of the dictionary
  62931. */
  62932. StringDictionary.prototype.clear = function () {
  62933. this._data = {};
  62934. this._count = 0;
  62935. };
  62936. Object.defineProperty(StringDictionary.prototype, "count", {
  62937. get: function () {
  62938. return this._count;
  62939. },
  62940. enumerable: true,
  62941. configurable: true
  62942. });
  62943. /**
  62944. * Execute a callback on each key/val of the dictionary.
  62945. * Note that you can remove any element in this dictionary in the callback implementation
  62946. * @param callback the callback to execute on a given key/value pair
  62947. */
  62948. StringDictionary.prototype.forEach = function (callback) {
  62949. for (var cur in this._data) {
  62950. var val = this._data[cur];
  62951. callback(cur, val);
  62952. }
  62953. };
  62954. /**
  62955. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62956. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62957. * Note that you can remove any element in this dictionary in the callback implementation
  62958. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62959. */
  62960. StringDictionary.prototype.first = function (callback) {
  62961. for (var cur in this._data) {
  62962. var val = this._data[cur];
  62963. var res = callback(cur, val);
  62964. if (res) {
  62965. return res;
  62966. }
  62967. }
  62968. return null;
  62969. };
  62970. return StringDictionary;
  62971. }());
  62972. BABYLON.StringDictionary = StringDictionary;
  62973. })(BABYLON || (BABYLON = {}));
  62974. //# sourceMappingURL=babylon.stringDictionary.js.map
  62975. var BABYLON;
  62976. (function (BABYLON) {
  62977. var Tags = /** @class */ (function () {
  62978. function Tags() {
  62979. }
  62980. Tags.EnableFor = function (obj) {
  62981. obj._tags = obj._tags || {};
  62982. obj.hasTags = function () {
  62983. return Tags.HasTags(obj);
  62984. };
  62985. obj.addTags = function (tagsString) {
  62986. return Tags.AddTagsTo(obj, tagsString);
  62987. };
  62988. obj.removeTags = function (tagsString) {
  62989. return Tags.RemoveTagsFrom(obj, tagsString);
  62990. };
  62991. obj.matchesTagsQuery = function (tagsQuery) {
  62992. return Tags.MatchesQuery(obj, tagsQuery);
  62993. };
  62994. };
  62995. Tags.DisableFor = function (obj) {
  62996. delete obj._tags;
  62997. delete obj.hasTags;
  62998. delete obj.addTags;
  62999. delete obj.removeTags;
  63000. delete obj.matchesTagsQuery;
  63001. };
  63002. Tags.HasTags = function (obj) {
  63003. if (!obj._tags) {
  63004. return false;
  63005. }
  63006. return !BABYLON.Tools.IsEmpty(obj._tags);
  63007. };
  63008. Tags.GetTags = function (obj, asString) {
  63009. if (asString === void 0) { asString = true; }
  63010. if (!obj._tags) {
  63011. return null;
  63012. }
  63013. if (asString) {
  63014. var tagsArray = [];
  63015. for (var tag in obj._tags) {
  63016. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  63017. tagsArray.push(tag);
  63018. }
  63019. }
  63020. return tagsArray.join(" ");
  63021. }
  63022. else {
  63023. return obj._tags;
  63024. }
  63025. };
  63026. // the tags 'true' and 'false' are reserved and cannot be used as tags
  63027. // a tag cannot start with '||', '&&', and '!'
  63028. // it cannot contain whitespaces
  63029. Tags.AddTagsTo = function (obj, tagsString) {
  63030. if (!tagsString) {
  63031. return;
  63032. }
  63033. if (typeof tagsString !== "string") {
  63034. return;
  63035. }
  63036. var tags = tagsString.split(" ");
  63037. tags.forEach(function (tag, index, array) {
  63038. Tags._AddTagTo(obj, tag);
  63039. });
  63040. };
  63041. Tags._AddTagTo = function (obj, tag) {
  63042. tag = tag.trim();
  63043. if (tag === "" || tag === "true" || tag === "false") {
  63044. return;
  63045. }
  63046. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  63047. return;
  63048. }
  63049. Tags.EnableFor(obj);
  63050. obj._tags[tag] = true;
  63051. };
  63052. Tags.RemoveTagsFrom = function (obj, tagsString) {
  63053. if (!Tags.HasTags(obj)) {
  63054. return;
  63055. }
  63056. var tags = tagsString.split(" ");
  63057. for (var t in tags) {
  63058. Tags._RemoveTagFrom(obj, tags[t]);
  63059. }
  63060. };
  63061. Tags._RemoveTagFrom = function (obj, tag) {
  63062. delete obj._tags[tag];
  63063. };
  63064. Tags.MatchesQuery = function (obj, tagsQuery) {
  63065. if (tagsQuery === undefined) {
  63066. return true;
  63067. }
  63068. if (tagsQuery === "") {
  63069. return Tags.HasTags(obj);
  63070. }
  63071. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  63072. };
  63073. return Tags;
  63074. }());
  63075. BABYLON.Tags = Tags;
  63076. })(BABYLON || (BABYLON = {}));
  63077. //# sourceMappingURL=babylon.tags.js.map
  63078. var BABYLON;
  63079. (function (BABYLON) {
  63080. var AndOrNotEvaluator = /** @class */ (function () {
  63081. function AndOrNotEvaluator() {
  63082. }
  63083. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  63084. if (!query.match(/\([^\(\)]*\)/g)) {
  63085. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  63086. }
  63087. else {
  63088. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  63089. // remove parenthesis
  63090. r = r.slice(1, r.length - 1);
  63091. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  63092. });
  63093. }
  63094. if (query === "true") {
  63095. return true;
  63096. }
  63097. if (query === "false") {
  63098. return false;
  63099. }
  63100. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  63101. };
  63102. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  63103. evaluateCallback = evaluateCallback || (function (r) {
  63104. return r === "true" ? true : false;
  63105. });
  63106. var result;
  63107. var or = parenthesisContent.split("||");
  63108. for (var i in or) {
  63109. if (or.hasOwnProperty(i)) {
  63110. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  63111. var and = ori.split("&&");
  63112. if (and.length > 1) {
  63113. for (var j = 0; j < and.length; ++j) {
  63114. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  63115. if (andj !== "true" && andj !== "false") {
  63116. if (andj[0] === "!") {
  63117. result = !evaluateCallback(andj.substring(1));
  63118. }
  63119. else {
  63120. result = evaluateCallback(andj);
  63121. }
  63122. }
  63123. else {
  63124. result = andj === "true" ? true : false;
  63125. }
  63126. if (!result) {
  63127. ori = "false";
  63128. break;
  63129. }
  63130. }
  63131. }
  63132. if (result || ori === "true") {
  63133. result = true;
  63134. break;
  63135. }
  63136. // result equals false (or undefined)
  63137. if (ori !== "true" && ori !== "false") {
  63138. if (ori[0] === "!") {
  63139. result = !evaluateCallback(ori.substring(1));
  63140. }
  63141. else {
  63142. result = evaluateCallback(ori);
  63143. }
  63144. }
  63145. else {
  63146. result = ori === "true" ? true : false;
  63147. }
  63148. }
  63149. }
  63150. // the whole parenthesis scope is replaced by 'true' or 'false'
  63151. return result ? "true" : "false";
  63152. };
  63153. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  63154. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  63155. // remove whitespaces
  63156. r = r.replace(/[\s]/g, function () { return ""; });
  63157. return r.length % 2 ? "!" : "";
  63158. });
  63159. booleanString = booleanString.trim();
  63160. if (booleanString === "!true") {
  63161. booleanString = "false";
  63162. }
  63163. else if (booleanString === "!false") {
  63164. booleanString = "true";
  63165. }
  63166. return booleanString;
  63167. };
  63168. return AndOrNotEvaluator;
  63169. }());
  63170. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  63171. })(BABYLON || (BABYLON = {}));
  63172. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  63173. var BABYLON;
  63174. (function (BABYLON) {
  63175. var Database = /** @class */ (function () {
  63176. function Database(urlToScene, callbackManifestChecked) {
  63177. // Handling various flavors of prefixed version of IndexedDB
  63178. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  63179. this.callbackManifestChecked = callbackManifestChecked;
  63180. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  63181. this.db = null;
  63182. this._enableSceneOffline = false;
  63183. this._enableTexturesOffline = false;
  63184. this.manifestVersionFound = 0;
  63185. this.mustUpdateRessources = false;
  63186. this.hasReachedQuota = false;
  63187. if (!Database.IDBStorageEnabled) {
  63188. this.callbackManifestChecked(true);
  63189. }
  63190. else {
  63191. this.checkManifestFile();
  63192. }
  63193. }
  63194. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  63195. get: function () {
  63196. return this._enableSceneOffline;
  63197. },
  63198. enumerable: true,
  63199. configurable: true
  63200. });
  63201. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  63202. get: function () {
  63203. return this._enableTexturesOffline;
  63204. },
  63205. enumerable: true,
  63206. configurable: true
  63207. });
  63208. Database.prototype.checkManifestFile = function () {
  63209. var _this = this;
  63210. var noManifestFile = function () {
  63211. _this._enableSceneOffline = false;
  63212. _this._enableTexturesOffline = false;
  63213. _this.callbackManifestChecked(false);
  63214. };
  63215. var timeStampUsed = false;
  63216. var manifestURL = this.currentSceneUrl + ".manifest";
  63217. var xhr = new XMLHttpRequest();
  63218. if (navigator.onLine) {
  63219. // Adding a timestamp to by-pass browsers' cache
  63220. timeStampUsed = true;
  63221. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  63222. }
  63223. xhr.open("GET", manifestURL, true);
  63224. xhr.addEventListener("load", function () {
  63225. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63226. try {
  63227. var manifestFile = JSON.parse(xhr.response);
  63228. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  63229. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  63230. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  63231. _this.manifestVersionFound = manifestFile.version;
  63232. }
  63233. if (_this.callbackManifestChecked) {
  63234. _this.callbackManifestChecked(true);
  63235. }
  63236. }
  63237. catch (ex) {
  63238. noManifestFile();
  63239. }
  63240. }
  63241. else {
  63242. noManifestFile();
  63243. }
  63244. }, false);
  63245. xhr.addEventListener("error", function (event) {
  63246. if (timeStampUsed) {
  63247. timeStampUsed = false;
  63248. // Let's retry without the timeStamp
  63249. // It could fail when coupled with HTML5 Offline API
  63250. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  63251. xhr.open("GET", retryManifestURL, true);
  63252. xhr.send();
  63253. }
  63254. else {
  63255. noManifestFile();
  63256. }
  63257. }, false);
  63258. try {
  63259. xhr.send();
  63260. }
  63261. catch (ex) {
  63262. BABYLON.Tools.Error("Error on XHR send request.");
  63263. this.callbackManifestChecked(false);
  63264. }
  63265. };
  63266. Database.prototype.openAsync = function (successCallback, errorCallback) {
  63267. var _this = this;
  63268. var handleError = function () {
  63269. _this.isSupported = false;
  63270. if (errorCallback)
  63271. errorCallback();
  63272. };
  63273. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  63274. // Your browser doesn't support IndexedDB
  63275. this.isSupported = false;
  63276. if (errorCallback)
  63277. errorCallback();
  63278. }
  63279. else {
  63280. // If the DB hasn't been opened or created yet
  63281. if (!this.db) {
  63282. this.hasReachedQuota = false;
  63283. this.isSupported = true;
  63284. var request = this.idbFactory.open("babylonjs", 1);
  63285. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  63286. request.onerror = function (event) {
  63287. handleError();
  63288. };
  63289. // executes when a version change transaction cannot complete due to other active transactions
  63290. request.onblocked = function (event) {
  63291. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  63292. handleError();
  63293. };
  63294. // DB has been opened successfully
  63295. request.onsuccess = function (event) {
  63296. _this.db = request.result;
  63297. successCallback();
  63298. };
  63299. // Initialization of the DB. Creating Scenes & Textures stores
  63300. request.onupgradeneeded = function (event) {
  63301. _this.db = (event.target).result;
  63302. if (_this.db) {
  63303. try {
  63304. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  63305. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  63306. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  63307. }
  63308. catch (ex) {
  63309. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  63310. handleError();
  63311. }
  63312. }
  63313. };
  63314. }
  63315. else {
  63316. if (successCallback)
  63317. successCallback();
  63318. }
  63319. }
  63320. };
  63321. Database.prototype.loadImageFromDB = function (url, image) {
  63322. var _this = this;
  63323. var completeURL = Database.ReturnFullUrlLocation(url);
  63324. var saveAndLoadImage = function () {
  63325. if (!_this.hasReachedQuota && _this.db !== null) {
  63326. // the texture is not yet in the DB, let's try to save it
  63327. _this._saveImageIntoDBAsync(completeURL, image);
  63328. }
  63329. else {
  63330. image.src = url;
  63331. }
  63332. };
  63333. if (!this.mustUpdateRessources) {
  63334. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  63335. }
  63336. else {
  63337. saveAndLoadImage();
  63338. }
  63339. };
  63340. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  63341. if (this.isSupported && this.db !== null) {
  63342. var texture;
  63343. var transaction = this.db.transaction(["textures"]);
  63344. transaction.onabort = function (event) {
  63345. image.src = url;
  63346. };
  63347. transaction.oncomplete = function (event) {
  63348. var blobTextureURL;
  63349. if (texture) {
  63350. var URL = window.URL || window.webkitURL;
  63351. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  63352. image.onerror = function () {
  63353. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  63354. image.src = url;
  63355. };
  63356. image.src = blobTextureURL;
  63357. }
  63358. else {
  63359. notInDBCallback();
  63360. }
  63361. };
  63362. var getRequest = transaction.objectStore("textures").get(url);
  63363. getRequest.onsuccess = function (event) {
  63364. texture = (event.target).result;
  63365. };
  63366. getRequest.onerror = function (event) {
  63367. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  63368. image.src = url;
  63369. };
  63370. }
  63371. else {
  63372. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63373. image.src = url;
  63374. }
  63375. };
  63376. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  63377. var _this = this;
  63378. if (this.isSupported) {
  63379. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  63380. var generateBlobUrl = function () {
  63381. var blobTextureURL;
  63382. if (blob) {
  63383. var URL = window.URL || window.webkitURL;
  63384. try {
  63385. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  63386. }
  63387. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  63388. catch (ex) {
  63389. blobTextureURL = URL.createObjectURL(blob);
  63390. }
  63391. }
  63392. if (blobTextureURL) {
  63393. image.src = blobTextureURL;
  63394. }
  63395. };
  63396. if (Database.IsUASupportingBlobStorage) {
  63397. var xhr = new XMLHttpRequest(), blob;
  63398. xhr.open("GET", url, true);
  63399. xhr.responseType = "blob";
  63400. xhr.addEventListener("load", function () {
  63401. if (xhr.status === 200 && _this.db) {
  63402. // Blob as response (XHR2)
  63403. blob = xhr.response;
  63404. var transaction = _this.db.transaction(["textures"], "readwrite");
  63405. // the transaction could abort because of a QuotaExceededError error
  63406. transaction.onabort = function (event) {
  63407. try {
  63408. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63409. var srcElement = (event.srcElement || event.target);
  63410. var error = srcElement.error;
  63411. if (error && error.name === "QuotaExceededError") {
  63412. _this.hasReachedQuota = true;
  63413. }
  63414. }
  63415. catch (ex) { }
  63416. generateBlobUrl();
  63417. };
  63418. transaction.oncomplete = function (event) {
  63419. generateBlobUrl();
  63420. };
  63421. var newTexture = { textureUrl: url, data: blob };
  63422. try {
  63423. // Put the blob into the dabase
  63424. var addRequest = transaction.objectStore("textures").put(newTexture);
  63425. addRequest.onsuccess = function (event) {
  63426. };
  63427. addRequest.onerror = function (event) {
  63428. generateBlobUrl();
  63429. };
  63430. }
  63431. catch (ex) {
  63432. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  63433. if (ex.code === 25) {
  63434. Database.IsUASupportingBlobStorage = false;
  63435. }
  63436. image.src = url;
  63437. }
  63438. }
  63439. else {
  63440. image.src = url;
  63441. }
  63442. }, false);
  63443. xhr.addEventListener("error", function (event) {
  63444. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  63445. image.src = url;
  63446. }, false);
  63447. xhr.send();
  63448. }
  63449. else {
  63450. image.src = url;
  63451. }
  63452. }
  63453. else {
  63454. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63455. image.src = url;
  63456. }
  63457. };
  63458. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  63459. var _this = this;
  63460. var updateVersion = function () {
  63461. // the version is not yet in the DB or we need to update it
  63462. _this._saveVersionIntoDBAsync(url, versionLoaded);
  63463. };
  63464. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  63465. };
  63466. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  63467. var _this = this;
  63468. if (this.isSupported && this.db) {
  63469. var version;
  63470. try {
  63471. var transaction = this.db.transaction(["versions"]);
  63472. transaction.oncomplete = function (event) {
  63473. if (version) {
  63474. // If the version in the JSON file is > than the version in DB
  63475. if (_this.manifestVersionFound > version.data) {
  63476. _this.mustUpdateRessources = true;
  63477. updateInDBCallback();
  63478. }
  63479. else {
  63480. callback(version.data);
  63481. }
  63482. }
  63483. else {
  63484. _this.mustUpdateRessources = true;
  63485. updateInDBCallback();
  63486. }
  63487. };
  63488. transaction.onabort = function (event) {
  63489. callback(-1);
  63490. };
  63491. var getRequest = transaction.objectStore("versions").get(url);
  63492. getRequest.onsuccess = function (event) {
  63493. version = (event.target).result;
  63494. };
  63495. getRequest.onerror = function (event) {
  63496. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  63497. callback(-1);
  63498. };
  63499. }
  63500. catch (ex) {
  63501. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  63502. callback(-1);
  63503. }
  63504. }
  63505. else {
  63506. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63507. callback(-1);
  63508. }
  63509. };
  63510. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  63511. var _this = this;
  63512. if (this.isSupported && !this.hasReachedQuota && this.db) {
  63513. try {
  63514. // Open a transaction to the database
  63515. var transaction = this.db.transaction(["versions"], "readwrite");
  63516. // the transaction could abort because of a QuotaExceededError error
  63517. transaction.onabort = function (event) {
  63518. try {
  63519. var error = event.srcElement['error'];
  63520. if (error && error.name === "QuotaExceededError") {
  63521. _this.hasReachedQuota = true;
  63522. }
  63523. }
  63524. catch (ex) { }
  63525. callback(-1);
  63526. };
  63527. transaction.oncomplete = function (event) {
  63528. callback(_this.manifestVersionFound);
  63529. };
  63530. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  63531. // Put the scene into the database
  63532. var addRequest = transaction.objectStore("versions").put(newVersion);
  63533. addRequest.onsuccess = function (event) {
  63534. };
  63535. addRequest.onerror = function (event) {
  63536. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  63537. };
  63538. }
  63539. catch (ex) {
  63540. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  63541. callback(-1);
  63542. }
  63543. }
  63544. else {
  63545. callback(-1);
  63546. }
  63547. };
  63548. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  63549. var _this = this;
  63550. var completeUrl = Database.ReturnFullUrlLocation(url);
  63551. var saveAndLoadFile = function () {
  63552. // the scene is not yet in the DB, let's try to save it
  63553. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  63554. };
  63555. this._checkVersionFromDB(completeUrl, function (version) {
  63556. if (version !== -1) {
  63557. if (!_this.mustUpdateRessources) {
  63558. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  63559. }
  63560. else {
  63561. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  63562. }
  63563. }
  63564. else {
  63565. if (errorCallback) {
  63566. errorCallback();
  63567. }
  63568. }
  63569. });
  63570. };
  63571. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  63572. if (this.isSupported && this.db) {
  63573. var targetStore;
  63574. if (url.indexOf(".babylon") !== -1) {
  63575. targetStore = "scenes";
  63576. }
  63577. else {
  63578. targetStore = "textures";
  63579. }
  63580. var file;
  63581. var transaction = this.db.transaction([targetStore]);
  63582. transaction.oncomplete = function (event) {
  63583. if (file) {
  63584. callback(file.data);
  63585. }
  63586. else {
  63587. notInDBCallback();
  63588. }
  63589. };
  63590. transaction.onabort = function (event) {
  63591. notInDBCallback();
  63592. };
  63593. var getRequest = transaction.objectStore(targetStore).get(url);
  63594. getRequest.onsuccess = function (event) {
  63595. file = (event.target).result;
  63596. };
  63597. getRequest.onerror = function (event) {
  63598. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  63599. notInDBCallback();
  63600. };
  63601. }
  63602. else {
  63603. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63604. callback();
  63605. }
  63606. };
  63607. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  63608. var _this = this;
  63609. if (this.isSupported) {
  63610. var targetStore;
  63611. if (url.indexOf(".babylon") !== -1) {
  63612. targetStore = "scenes";
  63613. }
  63614. else {
  63615. targetStore = "textures";
  63616. }
  63617. // Create XHR
  63618. var xhr = new XMLHttpRequest();
  63619. var fileData;
  63620. xhr.open("GET", url, true);
  63621. if (useArrayBuffer) {
  63622. xhr.responseType = "arraybuffer";
  63623. }
  63624. if (progressCallback) {
  63625. xhr.onprogress = progressCallback;
  63626. }
  63627. xhr.addEventListener("load", function () {
  63628. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  63629. // Blob as response (XHR2)
  63630. //fileData = xhr.responseText;
  63631. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  63632. if (!_this.hasReachedQuota && _this.db) {
  63633. // Open a transaction to the database
  63634. var transaction = _this.db.transaction([targetStore], "readwrite");
  63635. // the transaction could abort because of a QuotaExceededError error
  63636. transaction.onabort = function (event) {
  63637. try {
  63638. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63639. var error = event.srcElement['error'];
  63640. if (error && error.name === "QuotaExceededError") {
  63641. _this.hasReachedQuota = true;
  63642. }
  63643. }
  63644. catch (ex) { }
  63645. callback(fileData);
  63646. };
  63647. transaction.oncomplete = function (event) {
  63648. callback(fileData);
  63649. };
  63650. var newFile;
  63651. if (targetStore === "scenes") {
  63652. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  63653. }
  63654. else {
  63655. newFile = { textureUrl: url, data: fileData };
  63656. }
  63657. try {
  63658. // Put the scene into the database
  63659. var addRequest = transaction.objectStore(targetStore).put(newFile);
  63660. addRequest.onsuccess = function (event) {
  63661. };
  63662. addRequest.onerror = function (event) {
  63663. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  63664. };
  63665. }
  63666. catch (ex) {
  63667. callback(fileData);
  63668. }
  63669. }
  63670. else {
  63671. callback(fileData);
  63672. }
  63673. }
  63674. else {
  63675. callback();
  63676. }
  63677. }, false);
  63678. xhr.addEventListener("error", function (event) {
  63679. BABYLON.Tools.Error("error on XHR request.");
  63680. callback();
  63681. }, false);
  63682. xhr.send();
  63683. }
  63684. else {
  63685. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63686. callback();
  63687. }
  63688. };
  63689. Database.IsUASupportingBlobStorage = true;
  63690. Database.IDBStorageEnabled = true;
  63691. Database.parseURL = function (url) {
  63692. var a = document.createElement('a');
  63693. a.href = url;
  63694. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63695. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63696. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63697. return absLocation;
  63698. };
  63699. Database.ReturnFullUrlLocation = function (url) {
  63700. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63701. return (Database.parseURL(window.location.href) + url);
  63702. }
  63703. else {
  63704. return url;
  63705. }
  63706. };
  63707. return Database;
  63708. }());
  63709. BABYLON.Database = Database;
  63710. })(BABYLON || (BABYLON = {}));
  63711. //# sourceMappingURL=babylon.database.js.map
  63712. var BABYLON;
  63713. (function (BABYLON) {
  63714. var FresnelParameters = /** @class */ (function () {
  63715. function FresnelParameters() {
  63716. this._isEnabled = true;
  63717. this.leftColor = BABYLON.Color3.White();
  63718. this.rightColor = BABYLON.Color3.Black();
  63719. this.bias = 0;
  63720. this.power = 1;
  63721. }
  63722. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63723. get: function () {
  63724. return this._isEnabled;
  63725. },
  63726. set: function (value) {
  63727. if (this._isEnabled === value) {
  63728. return;
  63729. }
  63730. this._isEnabled = value;
  63731. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63732. },
  63733. enumerable: true,
  63734. configurable: true
  63735. });
  63736. FresnelParameters.prototype.clone = function () {
  63737. var newFresnelParameters = new FresnelParameters();
  63738. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63739. return newFresnelParameters;
  63740. };
  63741. FresnelParameters.prototype.serialize = function () {
  63742. var serializationObject = {};
  63743. serializationObject.isEnabled = this.isEnabled;
  63744. serializationObject.leftColor = this.leftColor;
  63745. serializationObject.rightColor = this.rightColor;
  63746. serializationObject.bias = this.bias;
  63747. serializationObject.power = this.power;
  63748. return serializationObject;
  63749. };
  63750. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63751. var fresnelParameters = new FresnelParameters();
  63752. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63753. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63754. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63755. fresnelParameters.bias = parsedFresnelParameters.bias;
  63756. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63757. return fresnelParameters;
  63758. };
  63759. return FresnelParameters;
  63760. }());
  63761. BABYLON.FresnelParameters = FresnelParameters;
  63762. })(BABYLON || (BABYLON = {}));
  63763. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63764. var BABYLON;
  63765. (function (BABYLON) {
  63766. var MultiMaterial = /** @class */ (function (_super) {
  63767. __extends(MultiMaterial, _super);
  63768. function MultiMaterial(name, scene) {
  63769. var _this = _super.call(this, name, scene, true) || this;
  63770. scene.multiMaterials.push(_this);
  63771. _this.subMaterials = new Array();
  63772. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63773. return _this;
  63774. }
  63775. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63776. get: function () {
  63777. return this._subMaterials;
  63778. },
  63779. set: function (value) {
  63780. this._subMaterials = value;
  63781. this._hookArray(value);
  63782. },
  63783. enumerable: true,
  63784. configurable: true
  63785. });
  63786. MultiMaterial.prototype._hookArray = function (array) {
  63787. var _this = this;
  63788. var oldPush = array.push;
  63789. array.push = function () {
  63790. var items = [];
  63791. for (var _i = 0; _i < arguments.length; _i++) {
  63792. items[_i] = arguments[_i];
  63793. }
  63794. var result = oldPush.apply(array, items);
  63795. _this._markAllSubMeshesAsTexturesDirty();
  63796. return result;
  63797. };
  63798. var oldSplice = array.splice;
  63799. array.splice = function (index, deleteCount) {
  63800. var deleted = oldSplice.apply(array, [index, deleteCount]);
  63801. _this._markAllSubMeshesAsTexturesDirty();
  63802. return deleted;
  63803. };
  63804. };
  63805. // Properties
  63806. MultiMaterial.prototype.getSubMaterial = function (index) {
  63807. if (index < 0 || index >= this.subMaterials.length) {
  63808. return this.getScene().defaultMaterial;
  63809. }
  63810. return this.subMaterials[index];
  63811. };
  63812. MultiMaterial.prototype.getActiveTextures = function () {
  63813. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  63814. if (subMaterial) {
  63815. return subMaterial.getActiveTextures();
  63816. }
  63817. else {
  63818. return [];
  63819. }
  63820. }));
  63821. var _a;
  63822. };
  63823. // Methods
  63824. MultiMaterial.prototype.getClassName = function () {
  63825. return "MultiMaterial";
  63826. };
  63827. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  63828. for (var index = 0; index < this.subMaterials.length; index++) {
  63829. var subMaterial = this.subMaterials[index];
  63830. if (subMaterial) {
  63831. if (subMaterial.storeEffectOnSubMeshes) {
  63832. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  63833. return false;
  63834. }
  63835. continue;
  63836. }
  63837. if (!subMaterial.isReady(mesh)) {
  63838. return false;
  63839. }
  63840. }
  63841. }
  63842. return true;
  63843. };
  63844. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63845. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63846. for (var index = 0; index < this.subMaterials.length; index++) {
  63847. var subMaterial = null;
  63848. var current = this.subMaterials[index];
  63849. if (cloneChildren && current) {
  63850. subMaterial = current.clone(name + "-" + current.name);
  63851. }
  63852. else {
  63853. subMaterial = this.subMaterials[index];
  63854. }
  63855. newMultiMaterial.subMaterials.push(subMaterial);
  63856. }
  63857. return newMultiMaterial;
  63858. };
  63859. MultiMaterial.prototype.serialize = function () {
  63860. var serializationObject = {};
  63861. serializationObject.name = this.name;
  63862. serializationObject.id = this.id;
  63863. if (BABYLON.Tags) {
  63864. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63865. }
  63866. serializationObject.materials = [];
  63867. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63868. var subMat = this.subMaterials[matIndex];
  63869. if (subMat) {
  63870. serializationObject.materials.push(subMat.id);
  63871. }
  63872. else {
  63873. serializationObject.materials.push(null);
  63874. }
  63875. }
  63876. return serializationObject;
  63877. };
  63878. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63879. var scene = this.getScene();
  63880. if (!scene) {
  63881. return;
  63882. }
  63883. var index = scene.multiMaterials.indexOf(this);
  63884. if (index >= 0) {
  63885. scene.multiMaterials.splice(index, 1);
  63886. }
  63887. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63888. };
  63889. return MultiMaterial;
  63890. }(BABYLON.Material));
  63891. BABYLON.MultiMaterial = MultiMaterial;
  63892. })(BABYLON || (BABYLON = {}));
  63893. //# sourceMappingURL=babylon.multiMaterial.js.map
  63894. var BABYLON;
  63895. (function (BABYLON) {
  63896. var FreeCameraTouchInput = /** @class */ (function () {
  63897. function FreeCameraTouchInput() {
  63898. this._offsetX = null;
  63899. this._offsetY = null;
  63900. this._pointerPressed = new Array();
  63901. this.touchAngularSensibility = 200000.0;
  63902. this.touchMoveSensibility = 250.0;
  63903. }
  63904. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63905. var _this = this;
  63906. var previousPosition = null;
  63907. if (this._pointerInput === undefined) {
  63908. this._onLostFocus = function (evt) {
  63909. _this._offsetX = null;
  63910. _this._offsetY = null;
  63911. };
  63912. this._pointerInput = function (p, s) {
  63913. var evt = p.event;
  63914. if (evt.pointerType === "mouse") {
  63915. return;
  63916. }
  63917. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63918. if (!noPreventDefault) {
  63919. evt.preventDefault();
  63920. }
  63921. _this._pointerPressed.push(evt.pointerId);
  63922. if (_this._pointerPressed.length !== 1) {
  63923. return;
  63924. }
  63925. previousPosition = {
  63926. x: evt.clientX,
  63927. y: evt.clientY
  63928. };
  63929. }
  63930. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63931. if (!noPreventDefault) {
  63932. evt.preventDefault();
  63933. }
  63934. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63935. if (index === -1) {
  63936. return;
  63937. }
  63938. _this._pointerPressed.splice(index, 1);
  63939. if (index != 0) {
  63940. return;
  63941. }
  63942. previousPosition = null;
  63943. _this._offsetX = null;
  63944. _this._offsetY = null;
  63945. }
  63946. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63947. if (!noPreventDefault) {
  63948. evt.preventDefault();
  63949. }
  63950. if (!previousPosition) {
  63951. return;
  63952. }
  63953. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63954. if (index != 0) {
  63955. return;
  63956. }
  63957. _this._offsetX = evt.clientX - previousPosition.x;
  63958. _this._offsetY = -(evt.clientY - previousPosition.y);
  63959. }
  63960. };
  63961. }
  63962. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63963. if (this._onLostFocus) {
  63964. element.addEventListener("blur", this._onLostFocus);
  63965. }
  63966. };
  63967. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63968. if (this._pointerInput && element) {
  63969. if (this._observer) {
  63970. this.camera.getScene().onPointerObservable.remove(this._observer);
  63971. this._observer = null;
  63972. }
  63973. if (this._onLostFocus) {
  63974. element.removeEventListener("blur", this._onLostFocus);
  63975. this._onLostFocus = null;
  63976. }
  63977. this._pointerPressed = [];
  63978. this._offsetX = null;
  63979. this._offsetY = null;
  63980. }
  63981. };
  63982. FreeCameraTouchInput.prototype.checkInputs = function () {
  63983. if (this._offsetX && this._offsetY) {
  63984. var camera = this.camera;
  63985. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63986. if (this._pointerPressed.length > 1) {
  63987. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63988. }
  63989. else {
  63990. var speed = camera._computeLocalCameraSpeed();
  63991. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63992. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63993. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63994. }
  63995. }
  63996. };
  63997. FreeCameraTouchInput.prototype.getClassName = function () {
  63998. return "FreeCameraTouchInput";
  63999. };
  64000. FreeCameraTouchInput.prototype.getSimpleName = function () {
  64001. return "touch";
  64002. };
  64003. __decorate([
  64004. BABYLON.serialize()
  64005. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64006. __decorate([
  64007. BABYLON.serialize()
  64008. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  64009. return FreeCameraTouchInput;
  64010. }());
  64011. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  64012. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  64013. })(BABYLON || (BABYLON = {}));
  64014. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  64015. var BABYLON;
  64016. (function (BABYLON) {
  64017. // We're mainly based on the logic defined into the FreeCamera code
  64018. var TouchCamera = /** @class */ (function (_super) {
  64019. __extends(TouchCamera, _super);
  64020. //-- end properties for backward compatibility for inputs
  64021. function TouchCamera(name, position, scene) {
  64022. var _this = _super.call(this, name, position, scene) || this;
  64023. _this.inputs.addTouch();
  64024. _this._setupInputs();
  64025. return _this;
  64026. }
  64027. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  64028. //-- Begin properties for backward compatibility for inputs
  64029. get: function () {
  64030. var touch = this.inputs.attached["touch"];
  64031. if (touch)
  64032. return touch.touchAngularSensibility;
  64033. return 0;
  64034. },
  64035. set: function (value) {
  64036. var touch = this.inputs.attached["touch"];
  64037. if (touch)
  64038. touch.touchAngularSensibility = value;
  64039. },
  64040. enumerable: true,
  64041. configurable: true
  64042. });
  64043. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  64044. get: function () {
  64045. var touch = this.inputs.attached["touch"];
  64046. if (touch)
  64047. return touch.touchMoveSensibility;
  64048. return 0;
  64049. },
  64050. set: function (value) {
  64051. var touch = this.inputs.attached["touch"];
  64052. if (touch)
  64053. touch.touchMoveSensibility = value;
  64054. },
  64055. enumerable: true,
  64056. configurable: true
  64057. });
  64058. TouchCamera.prototype.getClassName = function () {
  64059. return "TouchCamera";
  64060. };
  64061. TouchCamera.prototype._setupInputs = function () {
  64062. var mouse = this.inputs.attached["mouse"];
  64063. if (mouse) {
  64064. mouse.touchEnabled = false;
  64065. }
  64066. };
  64067. return TouchCamera;
  64068. }(BABYLON.FreeCamera));
  64069. BABYLON.TouchCamera = TouchCamera;
  64070. })(BABYLON || (BABYLON = {}));
  64071. //# sourceMappingURL=babylon.touchCamera.js.map
  64072. var BABYLON;
  64073. (function (BABYLON) {
  64074. var ProceduralTexture = /** @class */ (function (_super) {
  64075. __extends(ProceduralTexture, _super);
  64076. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  64077. if (fallbackTexture === void 0) { fallbackTexture = null; }
  64078. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64079. if (isCube === void 0) { isCube = false; }
  64080. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64081. _this.isCube = isCube;
  64082. _this.isEnabled = true;
  64083. _this._currentRefreshId = -1;
  64084. _this._refreshRate = 1;
  64085. _this._vertexBuffers = {};
  64086. _this._uniforms = new Array();
  64087. _this._samplers = new Array();
  64088. _this._textures = {};
  64089. _this._floats = {};
  64090. _this._floatsArrays = {};
  64091. _this._colors3 = {};
  64092. _this._colors4 = {};
  64093. _this._vectors2 = {};
  64094. _this._vectors3 = {};
  64095. _this._matrices = {};
  64096. _this._fallbackTextureUsed = false;
  64097. scene._proceduralTextures.push(_this);
  64098. _this._engine = scene.getEngine();
  64099. _this.name = name;
  64100. _this.isRenderTarget = true;
  64101. _this._size = size;
  64102. _this._generateMipMaps = generateMipMaps;
  64103. _this.setFragment(fragment);
  64104. _this._fallbackTexture = fallbackTexture;
  64105. if (isCube) {
  64106. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  64107. _this.setFloat("face", 0);
  64108. }
  64109. else {
  64110. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  64111. }
  64112. // VBO
  64113. var vertices = [];
  64114. vertices.push(1, 1);
  64115. vertices.push(-1, 1);
  64116. vertices.push(-1, -1);
  64117. vertices.push(1, -1);
  64118. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64119. _this._createIndexBuffer();
  64120. return _this;
  64121. }
  64122. ProceduralTexture.prototype._createIndexBuffer = function () {
  64123. var engine = this._engine;
  64124. // Indices
  64125. var indices = [];
  64126. indices.push(0);
  64127. indices.push(1);
  64128. indices.push(2);
  64129. indices.push(0);
  64130. indices.push(2);
  64131. indices.push(3);
  64132. this._indexBuffer = engine.createIndexBuffer(indices);
  64133. };
  64134. ProceduralTexture.prototype._rebuild = function () {
  64135. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64136. if (vb) {
  64137. vb._rebuild();
  64138. }
  64139. this._createIndexBuffer();
  64140. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64141. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64142. }
  64143. };
  64144. ProceduralTexture.prototype.reset = function () {
  64145. if (this._effect === undefined) {
  64146. return;
  64147. }
  64148. var engine = this._engine;
  64149. engine._releaseEffect(this._effect);
  64150. };
  64151. ProceduralTexture.prototype.isReady = function () {
  64152. var _this = this;
  64153. var engine = this._engine;
  64154. var shaders;
  64155. if (!this._fragment) {
  64156. return false;
  64157. }
  64158. if (this._fallbackTextureUsed) {
  64159. return true;
  64160. }
  64161. if (this._fragment.fragmentElement !== undefined) {
  64162. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  64163. }
  64164. else {
  64165. shaders = { vertex: "procedural", fragment: this._fragment };
  64166. }
  64167. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  64168. _this.releaseInternalTexture();
  64169. if (_this._fallbackTexture) {
  64170. _this._texture = _this._fallbackTexture._texture;
  64171. if (_this._texture) {
  64172. _this._texture.incrementReferences();
  64173. }
  64174. }
  64175. _this._fallbackTextureUsed = true;
  64176. });
  64177. return this._effect.isReady();
  64178. };
  64179. ProceduralTexture.prototype.resetRefreshCounter = function () {
  64180. this._currentRefreshId = -1;
  64181. };
  64182. ProceduralTexture.prototype.setFragment = function (fragment) {
  64183. this._fragment = fragment;
  64184. };
  64185. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  64186. get: function () {
  64187. return this._refreshRate;
  64188. },
  64189. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64190. set: function (value) {
  64191. this._refreshRate = value;
  64192. this.resetRefreshCounter();
  64193. },
  64194. enumerable: true,
  64195. configurable: true
  64196. });
  64197. ProceduralTexture.prototype._shouldRender = function () {
  64198. if (!this.isEnabled || !this.isReady() || !this._texture) {
  64199. return false;
  64200. }
  64201. if (this._fallbackTextureUsed) {
  64202. return false;
  64203. }
  64204. if (this._currentRefreshId === -1) {
  64205. this._currentRefreshId = 1;
  64206. return true;
  64207. }
  64208. if (this.refreshRate === this._currentRefreshId) {
  64209. this._currentRefreshId = 1;
  64210. return true;
  64211. }
  64212. this._currentRefreshId++;
  64213. return false;
  64214. };
  64215. ProceduralTexture.prototype.getRenderSize = function () {
  64216. return this._size;
  64217. };
  64218. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  64219. if (this._fallbackTextureUsed) {
  64220. return;
  64221. }
  64222. this.releaseInternalTexture();
  64223. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  64224. };
  64225. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  64226. if (this._uniforms.indexOf(uniformName) === -1) {
  64227. this._uniforms.push(uniformName);
  64228. }
  64229. };
  64230. ProceduralTexture.prototype.setTexture = function (name, texture) {
  64231. if (this._samplers.indexOf(name) === -1) {
  64232. this._samplers.push(name);
  64233. }
  64234. this._textures[name] = texture;
  64235. return this;
  64236. };
  64237. ProceduralTexture.prototype.setFloat = function (name, value) {
  64238. this._checkUniform(name);
  64239. this._floats[name] = value;
  64240. return this;
  64241. };
  64242. ProceduralTexture.prototype.setFloats = function (name, value) {
  64243. this._checkUniform(name);
  64244. this._floatsArrays[name] = value;
  64245. return this;
  64246. };
  64247. ProceduralTexture.prototype.setColor3 = function (name, value) {
  64248. this._checkUniform(name);
  64249. this._colors3[name] = value;
  64250. return this;
  64251. };
  64252. ProceduralTexture.prototype.setColor4 = function (name, value) {
  64253. this._checkUniform(name);
  64254. this._colors4[name] = value;
  64255. return this;
  64256. };
  64257. ProceduralTexture.prototype.setVector2 = function (name, value) {
  64258. this._checkUniform(name);
  64259. this._vectors2[name] = value;
  64260. return this;
  64261. };
  64262. ProceduralTexture.prototype.setVector3 = function (name, value) {
  64263. this._checkUniform(name);
  64264. this._vectors3[name] = value;
  64265. return this;
  64266. };
  64267. ProceduralTexture.prototype.setMatrix = function (name, value) {
  64268. this._checkUniform(name);
  64269. this._matrices[name] = value;
  64270. return this;
  64271. };
  64272. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64273. var scene = this.getScene();
  64274. if (!scene) {
  64275. return;
  64276. }
  64277. var engine = this._engine;
  64278. // Render
  64279. engine.enableEffect(this._effect);
  64280. engine.setState(false);
  64281. // Texture
  64282. for (var name in this._textures) {
  64283. this._effect.setTexture(name, this._textures[name]);
  64284. }
  64285. // Float
  64286. for (name in this._floats) {
  64287. this._effect.setFloat(name, this._floats[name]);
  64288. }
  64289. // Floats
  64290. for (name in this._floatsArrays) {
  64291. this._effect.setArray(name, this._floatsArrays[name]);
  64292. }
  64293. // Color3
  64294. for (name in this._colors3) {
  64295. this._effect.setColor3(name, this._colors3[name]);
  64296. }
  64297. // Color4
  64298. for (name in this._colors4) {
  64299. var color = this._colors4[name];
  64300. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64301. }
  64302. // Vector2
  64303. for (name in this._vectors2) {
  64304. this._effect.setVector2(name, this._vectors2[name]);
  64305. }
  64306. // Vector3
  64307. for (name in this._vectors3) {
  64308. this._effect.setVector3(name, this._vectors3[name]);
  64309. }
  64310. // Matrix
  64311. for (name in this._matrices) {
  64312. this._effect.setMatrix(name, this._matrices[name]);
  64313. }
  64314. if (!this._texture) {
  64315. return;
  64316. }
  64317. if (this.isCube) {
  64318. for (var face = 0; face < 6; face++) {
  64319. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  64320. // VBOs
  64321. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64322. this._effect.setFloat("face", face);
  64323. // Clear
  64324. engine.clear(scene.clearColor, true, true, true);
  64325. // Draw order
  64326. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64327. // Mipmaps
  64328. if (face === 5) {
  64329. engine.generateMipMapsForCubemap(this._texture);
  64330. }
  64331. }
  64332. }
  64333. else {
  64334. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  64335. // VBOs
  64336. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64337. // Clear
  64338. engine.clear(scene.clearColor, true, true, true);
  64339. // Draw order
  64340. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64341. }
  64342. // Unbind
  64343. engine.unBindFramebuffer(this._texture, this.isCube);
  64344. if (this.onGenerated) {
  64345. this.onGenerated();
  64346. }
  64347. };
  64348. ProceduralTexture.prototype.clone = function () {
  64349. var textureSize = this.getSize();
  64350. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  64351. // Base texture
  64352. newTexture.hasAlpha = this.hasAlpha;
  64353. newTexture.level = this.level;
  64354. // RenderTarget Texture
  64355. newTexture.coordinatesMode = this.coordinatesMode;
  64356. return newTexture;
  64357. };
  64358. ProceduralTexture.prototype.dispose = function () {
  64359. var scene = this.getScene();
  64360. if (!scene) {
  64361. return;
  64362. }
  64363. var index = scene._proceduralTextures.indexOf(this);
  64364. if (index >= 0) {
  64365. scene._proceduralTextures.splice(index, 1);
  64366. }
  64367. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64368. if (vertexBuffer) {
  64369. vertexBuffer.dispose();
  64370. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64371. }
  64372. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  64373. this._indexBuffer = null;
  64374. }
  64375. _super.prototype.dispose.call(this);
  64376. };
  64377. return ProceduralTexture;
  64378. }(BABYLON.Texture));
  64379. BABYLON.ProceduralTexture = ProceduralTexture;
  64380. })(BABYLON || (BABYLON = {}));
  64381. //# sourceMappingURL=babylon.proceduralTexture.js.map
  64382. var BABYLON;
  64383. (function (BABYLON) {
  64384. var CustomProceduralTexture = /** @class */ (function (_super) {
  64385. __extends(CustomProceduralTexture, _super);
  64386. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  64387. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  64388. _this._animate = true;
  64389. _this._time = 0;
  64390. _this._texturePath = texturePath;
  64391. //Try to load json
  64392. _this.loadJson(texturePath);
  64393. _this.refreshRate = 1;
  64394. return _this;
  64395. }
  64396. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  64397. var _this = this;
  64398. var noConfigFile = function () {
  64399. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  64400. try {
  64401. _this.setFragment(_this._texturePath);
  64402. }
  64403. catch (ex) {
  64404. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  64405. }
  64406. };
  64407. var configFileUrl = jsonUrl + "/config.json";
  64408. var xhr = new XMLHttpRequest();
  64409. xhr.open("GET", configFileUrl, true);
  64410. xhr.addEventListener("load", function () {
  64411. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64412. try {
  64413. _this._config = JSON.parse(xhr.response);
  64414. _this.updateShaderUniforms();
  64415. _this.updateTextures();
  64416. _this.setFragment(_this._texturePath + "/custom");
  64417. _this._animate = _this._config.animate;
  64418. _this.refreshRate = _this._config.refreshrate;
  64419. }
  64420. catch (ex) {
  64421. noConfigFile();
  64422. }
  64423. }
  64424. else {
  64425. noConfigFile();
  64426. }
  64427. }, false);
  64428. xhr.addEventListener("error", function () {
  64429. noConfigFile();
  64430. }, false);
  64431. try {
  64432. xhr.send();
  64433. }
  64434. catch (ex) {
  64435. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  64436. }
  64437. };
  64438. CustomProceduralTexture.prototype.isReady = function () {
  64439. if (!_super.prototype.isReady.call(this)) {
  64440. return false;
  64441. }
  64442. for (var name in this._textures) {
  64443. var texture = this._textures[name];
  64444. if (!texture.isReady()) {
  64445. return false;
  64446. }
  64447. }
  64448. return true;
  64449. };
  64450. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64451. var scene = this.getScene();
  64452. if (this._animate && scene) {
  64453. this._time += scene.getAnimationRatio() * 0.03;
  64454. this.updateShaderUniforms();
  64455. }
  64456. _super.prototype.render.call(this, useCameraPostProcess);
  64457. };
  64458. CustomProceduralTexture.prototype.updateTextures = function () {
  64459. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  64460. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  64461. }
  64462. };
  64463. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  64464. if (this._config) {
  64465. for (var j = 0; j < this._config.uniforms.length; j++) {
  64466. var uniform = this._config.uniforms[j];
  64467. switch (uniform.type) {
  64468. case "float":
  64469. this.setFloat(uniform.name, uniform.value);
  64470. break;
  64471. case "color3":
  64472. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  64473. break;
  64474. case "color4":
  64475. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  64476. break;
  64477. case "vector2":
  64478. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  64479. break;
  64480. case "vector3":
  64481. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  64482. break;
  64483. }
  64484. }
  64485. }
  64486. this.setFloat("time", this._time);
  64487. };
  64488. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  64489. get: function () {
  64490. return this._animate;
  64491. },
  64492. set: function (value) {
  64493. this._animate = value;
  64494. },
  64495. enumerable: true,
  64496. configurable: true
  64497. });
  64498. return CustomProceduralTexture;
  64499. }(BABYLON.ProceduralTexture));
  64500. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  64501. })(BABYLON || (BABYLON = {}));
  64502. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  64503. var BABYLON;
  64504. (function (BABYLON) {
  64505. var FreeCameraGamepadInput = /** @class */ (function () {
  64506. function FreeCameraGamepadInput() {
  64507. this.gamepadAngularSensibility = 200;
  64508. this.gamepadMoveSensibility = 40;
  64509. // private members
  64510. this._cameraTransform = BABYLON.Matrix.Identity();
  64511. this._deltaTransform = BABYLON.Vector3.Zero();
  64512. this._vector3 = BABYLON.Vector3.Zero();
  64513. this._vector2 = BABYLON.Vector2.Zero();
  64514. }
  64515. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64516. var _this = this;
  64517. var manager = this.camera.getScene().gamepadManager;
  64518. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64519. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64520. // prioritize XBOX gamepads.
  64521. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64522. _this.gamepad = gamepad;
  64523. }
  64524. }
  64525. });
  64526. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64527. if (_this.gamepad === gamepad) {
  64528. _this.gamepad = null;
  64529. }
  64530. });
  64531. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64532. };
  64533. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  64534. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64535. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64536. this.gamepad = null;
  64537. };
  64538. FreeCameraGamepadInput.prototype.checkInputs = function () {
  64539. if (this.gamepad && this.gamepad.leftStick) {
  64540. var camera = this.camera;
  64541. var LSValues = this.gamepad.leftStick;
  64542. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  64543. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64544. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  64545. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  64546. var RSValues = this.gamepad.rightStick;
  64547. if (RSValues) {
  64548. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  64549. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  64550. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  64551. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  64552. }
  64553. else {
  64554. RSValues = { x: 0, y: 0 };
  64555. }
  64556. if (!camera.rotationQuaternion) {
  64557. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  64558. }
  64559. else {
  64560. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  64561. }
  64562. var speed = camera._computeLocalCameraSpeed() * 50.0;
  64563. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  64564. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  64565. camera.cameraDirection.addInPlace(this._deltaTransform);
  64566. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  64567. camera.cameraRotation.addInPlace(this._vector2);
  64568. }
  64569. };
  64570. FreeCameraGamepadInput.prototype.getClassName = function () {
  64571. return "FreeCameraGamepadInput";
  64572. };
  64573. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  64574. return "gamepad";
  64575. };
  64576. __decorate([
  64577. BABYLON.serialize()
  64578. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  64579. __decorate([
  64580. BABYLON.serialize()
  64581. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64582. return FreeCameraGamepadInput;
  64583. }());
  64584. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  64585. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  64586. })(BABYLON || (BABYLON = {}));
  64587. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  64588. var BABYLON;
  64589. (function (BABYLON) {
  64590. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  64591. function ArcRotateCameraGamepadInput() {
  64592. this.gamepadRotationSensibility = 80;
  64593. this.gamepadMoveSensibility = 40;
  64594. }
  64595. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64596. var _this = this;
  64597. var manager = this.camera.getScene().gamepadManager;
  64598. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64599. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64600. // prioritize XBOX gamepads.
  64601. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64602. _this.gamepad = gamepad;
  64603. }
  64604. }
  64605. });
  64606. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64607. if (_this.gamepad === gamepad) {
  64608. _this.gamepad = null;
  64609. }
  64610. });
  64611. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64612. };
  64613. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  64614. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64615. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64616. this.gamepad = null;
  64617. };
  64618. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  64619. if (this.gamepad) {
  64620. var camera = this.camera;
  64621. var RSValues = this.gamepad.rightStick;
  64622. if (RSValues) {
  64623. if (RSValues.x != 0) {
  64624. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  64625. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  64626. camera.inertialAlphaOffset += normalizedRX;
  64627. }
  64628. }
  64629. if (RSValues.y != 0) {
  64630. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  64631. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  64632. camera.inertialBetaOffset += normalizedRY;
  64633. }
  64634. }
  64635. }
  64636. var LSValues = this.gamepad.leftStick;
  64637. if (LSValues && LSValues.y != 0) {
  64638. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64639. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  64640. this.camera.inertialRadiusOffset -= normalizedLY;
  64641. }
  64642. }
  64643. }
  64644. };
  64645. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  64646. return "ArcRotateCameraGamepadInput";
  64647. };
  64648. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  64649. return "gamepad";
  64650. };
  64651. __decorate([
  64652. BABYLON.serialize()
  64653. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  64654. __decorate([
  64655. BABYLON.serialize()
  64656. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64657. return ArcRotateCameraGamepadInput;
  64658. }());
  64659. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  64660. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  64661. })(BABYLON || (BABYLON = {}));
  64662. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  64663. var BABYLON;
  64664. (function (BABYLON) {
  64665. var GamepadManager = /** @class */ (function () {
  64666. function GamepadManager(_scene) {
  64667. var _this = this;
  64668. this._scene = _scene;
  64669. this._babylonGamepads = [];
  64670. this._oneGamepadConnected = false;
  64671. this._isMonitoring = false;
  64672. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  64673. if (!BABYLON.Tools.IsWindowObjectExist()) {
  64674. this._gamepadEventSupported = false;
  64675. }
  64676. else {
  64677. this._gamepadEventSupported = 'GamepadEvent' in window;
  64678. this._gamepadSupport = (navigator.getGamepads ||
  64679. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  64680. }
  64681. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64682. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64683. for (var i in _this._babylonGamepads) {
  64684. var gamepad = _this._babylonGamepads[i];
  64685. if (gamepad && gamepad._isConnected) {
  64686. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64687. }
  64688. }
  64689. });
  64690. this._onGamepadConnectedEvent = function (evt) {
  64691. var gamepad = evt.gamepad;
  64692. if (gamepad.index in _this._babylonGamepads) {
  64693. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64694. return;
  64695. }
  64696. }
  64697. var newGamepad;
  64698. if (_this._babylonGamepads[gamepad.index]) {
  64699. newGamepad = _this._babylonGamepads[gamepad.index];
  64700. newGamepad.browserGamepad = gamepad;
  64701. newGamepad._isConnected = true;
  64702. }
  64703. else {
  64704. newGamepad = _this._addNewGamepad(gamepad);
  64705. }
  64706. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64707. _this._startMonitoringGamepads();
  64708. };
  64709. this._onGamepadDisconnectedEvent = function (evt) {
  64710. var gamepad = evt.gamepad;
  64711. // Remove the gamepad from the list of gamepads to monitor.
  64712. for (var i in _this._babylonGamepads) {
  64713. if (_this._babylonGamepads[i].index === gamepad.index) {
  64714. var disconnectedGamepad = _this._babylonGamepads[i];
  64715. disconnectedGamepad._isConnected = false;
  64716. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64717. break;
  64718. }
  64719. }
  64720. };
  64721. if (this._gamepadSupport) {
  64722. //first add already-connected gamepads
  64723. this._updateGamepadObjects();
  64724. if (this._babylonGamepads.length) {
  64725. this._startMonitoringGamepads();
  64726. }
  64727. // Checking if the gamepad connected event is supported (like in Firefox)
  64728. if (this._gamepadEventSupported) {
  64729. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64730. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64731. }
  64732. else {
  64733. this._startMonitoringGamepads();
  64734. }
  64735. }
  64736. }
  64737. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64738. get: function () {
  64739. return this._babylonGamepads;
  64740. },
  64741. enumerable: true,
  64742. configurable: true
  64743. });
  64744. GamepadManager.prototype.getGamepadByType = function (type) {
  64745. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64746. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64747. var gamepad = _a[_i];
  64748. if (gamepad && gamepad.type === type) {
  64749. return gamepad;
  64750. }
  64751. }
  64752. return null;
  64753. };
  64754. GamepadManager.prototype.dispose = function () {
  64755. if (this._gamepadEventSupported) {
  64756. if (this._onGamepadConnectedEvent) {
  64757. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64758. }
  64759. if (this._onGamepadDisconnectedEvent) {
  64760. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64761. }
  64762. this._onGamepadConnectedEvent = null;
  64763. this._onGamepadDisconnectedEvent = null;
  64764. }
  64765. this._babylonGamepads.forEach(function (gamepad) {
  64766. gamepad.dispose();
  64767. });
  64768. this.onGamepadConnectedObservable.clear();
  64769. this.onGamepadDisconnectedObservable.clear();
  64770. this._oneGamepadConnected = false;
  64771. this._stopMonitoringGamepads();
  64772. this._babylonGamepads = [];
  64773. };
  64774. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64775. if (!this._oneGamepadConnected) {
  64776. this._oneGamepadConnected = true;
  64777. }
  64778. var newGamepad;
  64779. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64780. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64781. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64782. }
  64783. else if (gamepad.pose) {
  64784. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  64785. }
  64786. else {
  64787. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  64788. }
  64789. this._babylonGamepads[newGamepad.index] = newGamepad;
  64790. return newGamepad;
  64791. };
  64792. GamepadManager.prototype._startMonitoringGamepads = function () {
  64793. if (!this._isMonitoring) {
  64794. this._isMonitoring = true;
  64795. //back-comp
  64796. if (!this._scene) {
  64797. this._checkGamepadsStatus();
  64798. }
  64799. }
  64800. };
  64801. GamepadManager.prototype._stopMonitoringGamepads = function () {
  64802. this._isMonitoring = false;
  64803. };
  64804. GamepadManager.prototype._checkGamepadsStatus = function () {
  64805. var _this = this;
  64806. // Hack to be compatible Chrome
  64807. this._updateGamepadObjects();
  64808. for (var i in this._babylonGamepads) {
  64809. var gamepad = this._babylonGamepads[i];
  64810. if (!gamepad || !gamepad.isConnected) {
  64811. continue;
  64812. }
  64813. gamepad.update();
  64814. }
  64815. if (this._isMonitoring && !this._scene) {
  64816. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  64817. }
  64818. };
  64819. // This function is called only on Chrome, which does not properly support
  64820. // connection/disconnection events and forces you to recopy again the gamepad object
  64821. GamepadManager.prototype._updateGamepadObjects = function () {
  64822. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  64823. for (var i = 0; i < gamepads.length; i++) {
  64824. if (gamepads[i]) {
  64825. if (!this._babylonGamepads[gamepads[i].index]) {
  64826. var newGamepad = this._addNewGamepad(gamepads[i]);
  64827. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64828. }
  64829. else {
  64830. // Forced to copy again this object for Chrome for unknown reason
  64831. this._babylonGamepads[i].browserGamepad = gamepads[i];
  64832. if (!this._babylonGamepads[i].isConnected) {
  64833. this._babylonGamepads[i]._isConnected = true;
  64834. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  64835. }
  64836. }
  64837. }
  64838. }
  64839. };
  64840. return GamepadManager;
  64841. }());
  64842. BABYLON.GamepadManager = GamepadManager;
  64843. })(BABYLON || (BABYLON = {}));
  64844. //# sourceMappingURL=babylon.gamepadManager.js.map
  64845. var BABYLON;
  64846. (function (BABYLON) {
  64847. var StickValues = /** @class */ (function () {
  64848. function StickValues(x, y) {
  64849. this.x = x;
  64850. this.y = y;
  64851. }
  64852. return StickValues;
  64853. }());
  64854. BABYLON.StickValues = StickValues;
  64855. var Gamepad = /** @class */ (function () {
  64856. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64857. if (leftStickX === void 0) { leftStickX = 0; }
  64858. if (leftStickY === void 0) { leftStickY = 1; }
  64859. if (rightStickX === void 0) { rightStickX = 2; }
  64860. if (rightStickY === void 0) { rightStickY = 3; }
  64861. this.id = id;
  64862. this.index = index;
  64863. this.browserGamepad = browserGamepad;
  64864. this._isConnected = true;
  64865. this._invertLeftStickY = false;
  64866. this.type = Gamepad.GAMEPAD;
  64867. this._leftStickAxisX = leftStickX;
  64868. this._leftStickAxisY = leftStickY;
  64869. this._rightStickAxisX = rightStickX;
  64870. this._rightStickAxisY = rightStickY;
  64871. if (this.browserGamepad.axes.length >= 2) {
  64872. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64873. }
  64874. if (this.browserGamepad.axes.length >= 4) {
  64875. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64876. }
  64877. }
  64878. Object.defineProperty(Gamepad.prototype, "isConnected", {
  64879. get: function () {
  64880. return this._isConnected;
  64881. },
  64882. enumerable: true,
  64883. configurable: true
  64884. });
  64885. Gamepad.prototype.onleftstickchanged = function (callback) {
  64886. this._onleftstickchanged = callback;
  64887. };
  64888. Gamepad.prototype.onrightstickchanged = function (callback) {
  64889. this._onrightstickchanged = callback;
  64890. };
  64891. Object.defineProperty(Gamepad.prototype, "leftStick", {
  64892. get: function () {
  64893. return this._leftStick;
  64894. },
  64895. set: function (newValues) {
  64896. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64897. this._onleftstickchanged(newValues);
  64898. }
  64899. this._leftStick = newValues;
  64900. },
  64901. enumerable: true,
  64902. configurable: true
  64903. });
  64904. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64905. get: function () {
  64906. return this._rightStick;
  64907. },
  64908. set: function (newValues) {
  64909. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64910. this._onrightstickchanged(newValues);
  64911. }
  64912. this._rightStick = newValues;
  64913. },
  64914. enumerable: true,
  64915. configurable: true
  64916. });
  64917. Gamepad.prototype.update = function () {
  64918. if (this._leftStick) {
  64919. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64920. if (this._invertLeftStickY) {
  64921. this.leftStick.y *= -1;
  64922. }
  64923. }
  64924. if (this._rightStick) {
  64925. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64926. }
  64927. };
  64928. Gamepad.prototype.dispose = function () {
  64929. };
  64930. Gamepad.GAMEPAD = 0;
  64931. Gamepad.GENERIC = 1;
  64932. Gamepad.XBOX = 2;
  64933. Gamepad.POSE_ENABLED = 3;
  64934. return Gamepad;
  64935. }());
  64936. BABYLON.Gamepad = Gamepad;
  64937. var GenericPad = /** @class */ (function (_super) {
  64938. __extends(GenericPad, _super);
  64939. function GenericPad(id, index, browserGamepad) {
  64940. var _this = _super.call(this, id, index, browserGamepad) || this;
  64941. _this.onButtonDownObservable = new BABYLON.Observable();
  64942. _this.onButtonUpObservable = new BABYLON.Observable();
  64943. _this.type = Gamepad.GENERIC;
  64944. _this._buttons = new Array(browserGamepad.buttons.length);
  64945. return _this;
  64946. }
  64947. GenericPad.prototype.onbuttondown = function (callback) {
  64948. this._onbuttondown = callback;
  64949. };
  64950. GenericPad.prototype.onbuttonup = function (callback) {
  64951. this._onbuttonup = callback;
  64952. };
  64953. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64954. if (newValue !== currentValue) {
  64955. if (newValue === 1) {
  64956. if (this._onbuttondown) {
  64957. this._onbuttondown(buttonIndex);
  64958. }
  64959. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64960. }
  64961. if (newValue === 0) {
  64962. if (this._onbuttonup) {
  64963. this._onbuttonup(buttonIndex);
  64964. }
  64965. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64966. }
  64967. }
  64968. return newValue;
  64969. };
  64970. GenericPad.prototype.update = function () {
  64971. _super.prototype.update.call(this);
  64972. for (var index = 0; index < this._buttons.length; index++) {
  64973. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64974. }
  64975. };
  64976. GenericPad.prototype.dispose = function () {
  64977. _super.prototype.dispose.call(this);
  64978. this.onButtonDownObservable.clear();
  64979. this.onButtonUpObservable.clear();
  64980. };
  64981. return GenericPad;
  64982. }(Gamepad));
  64983. BABYLON.GenericPad = GenericPad;
  64984. })(BABYLON || (BABYLON = {}));
  64985. //# sourceMappingURL=babylon.gamepad.js.map
  64986. var BABYLON;
  64987. (function (BABYLON) {
  64988. var Xbox360Button;
  64989. (function (Xbox360Button) {
  64990. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64991. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64992. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64993. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64994. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64995. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64996. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64997. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64998. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64999. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  65000. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  65001. var Xbox360Dpad;
  65002. (function (Xbox360Dpad) {
  65003. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  65004. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  65005. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  65006. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  65007. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  65008. var Xbox360Pad = /** @class */ (function (_super) {
  65009. __extends(Xbox360Pad, _super);
  65010. function Xbox360Pad(id, index, gamepad, xboxOne) {
  65011. if (xboxOne === void 0) { xboxOne = false; }
  65012. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  65013. _this._leftTrigger = 0;
  65014. _this._rightTrigger = 0;
  65015. _this.onButtonDownObservable = new BABYLON.Observable();
  65016. _this.onButtonUpObservable = new BABYLON.Observable();
  65017. _this.onPadDownObservable = new BABYLON.Observable();
  65018. _this.onPadUpObservable = new BABYLON.Observable();
  65019. _this._buttonA = 0;
  65020. _this._buttonB = 0;
  65021. _this._buttonX = 0;
  65022. _this._buttonY = 0;
  65023. _this._buttonBack = 0;
  65024. _this._buttonStart = 0;
  65025. _this._buttonLB = 0;
  65026. _this._buttonRB = 0;
  65027. _this._buttonLeftStick = 0;
  65028. _this._buttonRightStick = 0;
  65029. _this._dPadUp = 0;
  65030. _this._dPadDown = 0;
  65031. _this._dPadLeft = 0;
  65032. _this._dPadRight = 0;
  65033. _this._isXboxOnePad = false;
  65034. _this.type = BABYLON.Gamepad.XBOX;
  65035. _this._isXboxOnePad = xboxOne;
  65036. return _this;
  65037. }
  65038. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  65039. this._onlefttriggerchanged = callback;
  65040. };
  65041. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  65042. this._onrighttriggerchanged = callback;
  65043. };
  65044. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  65045. get: function () {
  65046. return this._leftTrigger;
  65047. },
  65048. set: function (newValue) {
  65049. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  65050. this._onlefttriggerchanged(newValue);
  65051. }
  65052. this._leftTrigger = newValue;
  65053. },
  65054. enumerable: true,
  65055. configurable: true
  65056. });
  65057. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  65058. get: function () {
  65059. return this._rightTrigger;
  65060. },
  65061. set: function (newValue) {
  65062. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  65063. this._onrighttriggerchanged(newValue);
  65064. }
  65065. this._rightTrigger = newValue;
  65066. },
  65067. enumerable: true,
  65068. configurable: true
  65069. });
  65070. Xbox360Pad.prototype.onbuttondown = function (callback) {
  65071. this._onbuttondown = callback;
  65072. };
  65073. Xbox360Pad.prototype.onbuttonup = function (callback) {
  65074. this._onbuttonup = callback;
  65075. };
  65076. Xbox360Pad.prototype.ondpaddown = function (callback) {
  65077. this._ondpaddown = callback;
  65078. };
  65079. Xbox360Pad.prototype.ondpadup = function (callback) {
  65080. this._ondpadup = callback;
  65081. };
  65082. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  65083. if (newValue !== currentValue) {
  65084. if (newValue === 1) {
  65085. if (this._onbuttondown) {
  65086. this._onbuttondown(buttonType);
  65087. }
  65088. this.onButtonDownObservable.notifyObservers(buttonType);
  65089. }
  65090. if (newValue === 0) {
  65091. if (this._onbuttonup) {
  65092. this._onbuttonup(buttonType);
  65093. }
  65094. this.onButtonUpObservable.notifyObservers(buttonType);
  65095. }
  65096. }
  65097. return newValue;
  65098. };
  65099. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  65100. if (newValue !== currentValue) {
  65101. if (newValue === 1) {
  65102. if (this._ondpaddown) {
  65103. this._ondpaddown(buttonType);
  65104. }
  65105. this.onPadDownObservable.notifyObservers(buttonType);
  65106. }
  65107. if (newValue === 0) {
  65108. if (this._ondpadup) {
  65109. this._ondpadup(buttonType);
  65110. }
  65111. this.onPadUpObservable.notifyObservers(buttonType);
  65112. }
  65113. }
  65114. return newValue;
  65115. };
  65116. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  65117. get: function () {
  65118. return this._buttonA;
  65119. },
  65120. set: function (value) {
  65121. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  65122. },
  65123. enumerable: true,
  65124. configurable: true
  65125. });
  65126. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  65127. get: function () {
  65128. return this._buttonB;
  65129. },
  65130. set: function (value) {
  65131. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  65132. },
  65133. enumerable: true,
  65134. configurable: true
  65135. });
  65136. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  65137. get: function () {
  65138. return this._buttonX;
  65139. },
  65140. set: function (value) {
  65141. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  65142. },
  65143. enumerable: true,
  65144. configurable: true
  65145. });
  65146. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  65147. get: function () {
  65148. return this._buttonY;
  65149. },
  65150. set: function (value) {
  65151. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  65152. },
  65153. enumerable: true,
  65154. configurable: true
  65155. });
  65156. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  65157. get: function () {
  65158. return this._buttonStart;
  65159. },
  65160. set: function (value) {
  65161. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  65162. },
  65163. enumerable: true,
  65164. configurable: true
  65165. });
  65166. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  65167. get: function () {
  65168. return this._buttonBack;
  65169. },
  65170. set: function (value) {
  65171. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  65172. },
  65173. enumerable: true,
  65174. configurable: true
  65175. });
  65176. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  65177. get: function () {
  65178. return this._buttonLB;
  65179. },
  65180. set: function (value) {
  65181. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  65182. },
  65183. enumerable: true,
  65184. configurable: true
  65185. });
  65186. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  65187. get: function () {
  65188. return this._buttonRB;
  65189. },
  65190. set: function (value) {
  65191. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  65192. },
  65193. enumerable: true,
  65194. configurable: true
  65195. });
  65196. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  65197. get: function () {
  65198. return this._buttonLeftStick;
  65199. },
  65200. set: function (value) {
  65201. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  65202. },
  65203. enumerable: true,
  65204. configurable: true
  65205. });
  65206. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  65207. get: function () {
  65208. return this._buttonRightStick;
  65209. },
  65210. set: function (value) {
  65211. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  65212. },
  65213. enumerable: true,
  65214. configurable: true
  65215. });
  65216. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  65217. get: function () {
  65218. return this._dPadUp;
  65219. },
  65220. set: function (value) {
  65221. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  65222. },
  65223. enumerable: true,
  65224. configurable: true
  65225. });
  65226. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  65227. get: function () {
  65228. return this._dPadDown;
  65229. },
  65230. set: function (value) {
  65231. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  65232. },
  65233. enumerable: true,
  65234. configurable: true
  65235. });
  65236. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  65237. get: function () {
  65238. return this._dPadLeft;
  65239. },
  65240. set: function (value) {
  65241. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  65242. },
  65243. enumerable: true,
  65244. configurable: true
  65245. });
  65246. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  65247. get: function () {
  65248. return this._dPadRight;
  65249. },
  65250. set: function (value) {
  65251. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  65252. },
  65253. enumerable: true,
  65254. configurable: true
  65255. });
  65256. Xbox360Pad.prototype.update = function () {
  65257. _super.prototype.update.call(this);
  65258. if (this._isXboxOnePad) {
  65259. this.buttonA = this.browserGamepad.buttons[0].value;
  65260. this.buttonB = this.browserGamepad.buttons[1].value;
  65261. this.buttonX = this.browserGamepad.buttons[2].value;
  65262. this.buttonY = this.browserGamepad.buttons[3].value;
  65263. this.buttonLB = this.browserGamepad.buttons[4].value;
  65264. this.buttonRB = this.browserGamepad.buttons[5].value;
  65265. this.leftTrigger = this.browserGamepad.axes[2];
  65266. this.rightTrigger = this.browserGamepad.axes[5];
  65267. this.buttonBack = this.browserGamepad.buttons[9].value;
  65268. this.buttonStart = this.browserGamepad.buttons[8].value;
  65269. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  65270. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  65271. this.dPadUp = this.browserGamepad.buttons[11].value;
  65272. this.dPadDown = this.browserGamepad.buttons[12].value;
  65273. this.dPadLeft = this.browserGamepad.buttons[13].value;
  65274. this.dPadRight = this.browserGamepad.buttons[14].value;
  65275. }
  65276. else {
  65277. this.buttonA = this.browserGamepad.buttons[0].value;
  65278. this.buttonB = this.browserGamepad.buttons[1].value;
  65279. this.buttonX = this.browserGamepad.buttons[2].value;
  65280. this.buttonY = this.browserGamepad.buttons[3].value;
  65281. this.buttonLB = this.browserGamepad.buttons[4].value;
  65282. this.buttonRB = this.browserGamepad.buttons[5].value;
  65283. this.leftTrigger = this.browserGamepad.buttons[6].value;
  65284. this.rightTrigger = this.browserGamepad.buttons[7].value;
  65285. this.buttonBack = this.browserGamepad.buttons[8].value;
  65286. this.buttonStart = this.browserGamepad.buttons[9].value;
  65287. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  65288. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  65289. this.dPadUp = this.browserGamepad.buttons[12].value;
  65290. this.dPadDown = this.browserGamepad.buttons[13].value;
  65291. this.dPadLeft = this.browserGamepad.buttons[14].value;
  65292. this.dPadRight = this.browserGamepad.buttons[15].value;
  65293. }
  65294. };
  65295. Xbox360Pad.prototype.dispose = function () {
  65296. _super.prototype.dispose.call(this);
  65297. this.onButtonDownObservable.clear();
  65298. this.onButtonUpObservable.clear();
  65299. this.onPadDownObservable.clear();
  65300. this.onPadUpObservable.clear();
  65301. };
  65302. return Xbox360Pad;
  65303. }(BABYLON.Gamepad));
  65304. BABYLON.Xbox360Pad = Xbox360Pad;
  65305. })(BABYLON || (BABYLON = {}));
  65306. //# sourceMappingURL=babylon.xboxGamepad.js.map
  65307. var BABYLON;
  65308. (function (BABYLON) {
  65309. var PoseEnabledControllerType;
  65310. (function (PoseEnabledControllerType) {
  65311. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  65312. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  65313. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  65314. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  65315. /**
  65316. * Google Daydream
  65317. */
  65318. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  65319. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  65320. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  65321. var PoseEnabledControllerHelper = /** @class */ (function () {
  65322. function PoseEnabledControllerHelper() {
  65323. }
  65324. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  65325. // Oculus Touch
  65326. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  65327. return new BABYLON.OculusTouchController(vrGamepad);
  65328. }
  65329. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  65330. return new BABYLON.WindowsMotionController(vrGamepad);
  65331. }
  65332. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  65333. return new BABYLON.ViveController(vrGamepad);
  65334. }
  65335. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  65336. return new BABYLON.GearVRController(vrGamepad);
  65337. }
  65338. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  65339. return new BABYLON.DaydreamController(vrGamepad);
  65340. }
  65341. else {
  65342. return new BABYLON.GenericController(vrGamepad);
  65343. }
  65344. };
  65345. return PoseEnabledControllerHelper;
  65346. }());
  65347. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  65348. var PoseEnabledController = /** @class */ (function (_super) {
  65349. __extends(PoseEnabledController, _super);
  65350. function PoseEnabledController(browserGamepad) {
  65351. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  65352. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  65353. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  65354. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  65355. // Represents device position and rotation in babylon space
  65356. _this.devicePosition = BABYLON.Vector3.Zero();
  65357. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65358. _this.deviceScaleFactor = 1;
  65359. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  65360. _this._deviceToWorld = BABYLON.Matrix.Identity();
  65361. /**
  65362. * Node to be used when casting a ray from the controller
  65363. */
  65364. _this._pointingPoseNode = null;
  65365. _this._workingMatrix = BABYLON.Matrix.Identity();
  65366. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  65367. _this.controllerType = PoseEnabledControllerType.GENERIC;
  65368. _this.position = BABYLON.Vector3.Zero();
  65369. _this.rotationQuaternion = new BABYLON.Quaternion();
  65370. _this._calculatedPosition = BABYLON.Vector3.Zero();
  65371. _this._calculatedRotation = new BABYLON.Quaternion();
  65372. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  65373. return _this;
  65374. }
  65375. PoseEnabledController.prototype.update = function () {
  65376. _super.prototype.update.call(this);
  65377. var pose = this.browserGamepad.pose;
  65378. this.updateFromDevice(pose);
  65379. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  65380. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  65381. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  65382. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  65383. if (this._mesh) {
  65384. this._mesh.position.copyFrom(this.devicePosition);
  65385. if (this._mesh.rotationQuaternion) {
  65386. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65387. }
  65388. }
  65389. };
  65390. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  65391. if (poseData) {
  65392. this.rawPose = poseData;
  65393. if (poseData.position) {
  65394. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  65395. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  65396. this._deviceRoomPosition.z *= -1;
  65397. }
  65398. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  65399. this._calculatedPosition.addInPlace(this.position);
  65400. }
  65401. var pose = this.rawPose;
  65402. if (poseData.orientation && pose.orientation) {
  65403. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  65404. if (this._mesh) {
  65405. if (this._mesh.getScene().useRightHandedSystem) {
  65406. this._deviceRoomRotationQuaternion.z *= -1;
  65407. this._deviceRoomRotationQuaternion.w *= -1;
  65408. }
  65409. else {
  65410. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  65411. }
  65412. }
  65413. // if the camera is set, rotate to the camera's rotation
  65414. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  65415. }
  65416. }
  65417. };
  65418. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  65419. if (this._mesh) {
  65420. this._mesh.parent = null;
  65421. }
  65422. this._mesh = mesh;
  65423. if (this._poseControlledCamera) {
  65424. this._mesh.parent = this._poseControlledCamera;
  65425. }
  65426. if (!this._mesh.rotationQuaternion) {
  65427. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  65428. }
  65429. };
  65430. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  65431. this._poseControlledCamera = camera;
  65432. if (this._mesh) {
  65433. this._mesh.parent = this._poseControlledCamera;
  65434. }
  65435. };
  65436. PoseEnabledController.prototype.dispose = function () {
  65437. if (this._mesh) {
  65438. this._mesh.dispose();
  65439. }
  65440. this._mesh = null;
  65441. _super.prototype.dispose.call(this);
  65442. };
  65443. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  65444. get: function () {
  65445. return this._mesh;
  65446. },
  65447. enumerable: true,
  65448. configurable: true
  65449. });
  65450. PoseEnabledController.prototype.getForwardRay = function (length) {
  65451. if (length === void 0) { length = 100; }
  65452. if (!this.mesh) {
  65453. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  65454. }
  65455. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  65456. var origin = m.getTranslation();
  65457. var forward = new BABYLON.Vector3(0, 0, -1);
  65458. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65459. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65460. return new BABYLON.Ray(origin, direction, length);
  65461. };
  65462. /**
  65463. * Name of the child mesh that can be used to cast a ray from the controller
  65464. */
  65465. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  65466. return PoseEnabledController;
  65467. }(BABYLON.Gamepad));
  65468. BABYLON.PoseEnabledController = PoseEnabledController;
  65469. })(BABYLON || (BABYLON = {}));
  65470. //# sourceMappingURL=babylon.poseEnabledController.js.map
  65471. var BABYLON;
  65472. (function (BABYLON) {
  65473. var WebVRController = /** @class */ (function (_super) {
  65474. __extends(WebVRController, _super);
  65475. function WebVRController(vrGamepad) {
  65476. var _this = _super.call(this, vrGamepad) || this;
  65477. // Observables
  65478. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  65479. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  65480. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  65481. _this.onPadStateChangedObservable = new BABYLON.Observable();
  65482. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  65483. _this.pad = { x: 0, y: 0 };
  65484. // avoid GC, store state in a tmp object
  65485. _this._changes = {
  65486. pressChanged: false,
  65487. touchChanged: false,
  65488. valueChanged: false,
  65489. changed: false
  65490. };
  65491. _this._buttons = new Array(vrGamepad.buttons.length);
  65492. _this.hand = vrGamepad.hand;
  65493. return _this;
  65494. }
  65495. WebVRController.prototype.onButtonStateChange = function (callback) {
  65496. this._onButtonStateChange = callback;
  65497. };
  65498. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  65499. get: function () {
  65500. return this._defaultModel;
  65501. },
  65502. enumerable: true,
  65503. configurable: true
  65504. });
  65505. WebVRController.prototype.update = function () {
  65506. _super.prototype.update.call(this);
  65507. for (var index = 0; index < this._buttons.length; index++) {
  65508. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  65509. }
  65510. ;
  65511. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  65512. this.pad.x = this.leftStick.x;
  65513. this.pad.y = this.leftStick.y;
  65514. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  65515. }
  65516. };
  65517. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  65518. if (!newState) {
  65519. newState = {
  65520. pressed: false,
  65521. touched: false,
  65522. value: 0
  65523. };
  65524. }
  65525. if (!currentState) {
  65526. this._buttons[buttonIndex] = {
  65527. pressed: newState.pressed,
  65528. touched: newState.touched,
  65529. value: newState.value
  65530. };
  65531. return;
  65532. }
  65533. this._checkChanges(newState, currentState);
  65534. if (this._changes.changed) {
  65535. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  65536. this._handleButtonChange(buttonIndex, newState, this._changes);
  65537. }
  65538. this._buttons[buttonIndex].pressed = newState.pressed;
  65539. this._buttons[buttonIndex].touched = newState.touched;
  65540. // oculus triggers are never 0, thou not touched.
  65541. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  65542. };
  65543. WebVRController.prototype._checkChanges = function (newState, currentState) {
  65544. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  65545. this._changes.touchChanged = newState.touched !== currentState.touched;
  65546. this._changes.valueChanged = newState.value !== currentState.value;
  65547. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  65548. return this._changes;
  65549. };
  65550. WebVRController.prototype.dispose = function () {
  65551. _super.prototype.dispose.call(this);
  65552. this.onTriggerStateChangedObservable.clear();
  65553. this.onMainButtonStateChangedObservable.clear();
  65554. this.onSecondaryButtonStateChangedObservable.clear();
  65555. this.onPadStateChangedObservable.clear();
  65556. this.onPadValuesChangedObservable.clear();
  65557. };
  65558. return WebVRController;
  65559. }(BABYLON.PoseEnabledController));
  65560. BABYLON.WebVRController = WebVRController;
  65561. })(BABYLON || (BABYLON = {}));
  65562. //# sourceMappingURL=babylon.webVRController.js.map
  65563. var BABYLON;
  65564. (function (BABYLON) {
  65565. var OculusTouchController = /** @class */ (function (_super) {
  65566. __extends(OculusTouchController, _super);
  65567. function OculusTouchController(vrGamepad) {
  65568. var _this = _super.call(this, vrGamepad) || this;
  65569. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  65570. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  65571. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  65572. return _this;
  65573. }
  65574. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65575. var _this = this;
  65576. var meshName;
  65577. // Hand
  65578. if (this.hand === 'left') {
  65579. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  65580. }
  65581. else {
  65582. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  65583. }
  65584. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  65585. /*
  65586. Parent Mesh name: oculus_touch_left
  65587. - body
  65588. - trigger
  65589. - thumbstick
  65590. - grip
  65591. - button_y
  65592. - button_x
  65593. - button_enter
  65594. */
  65595. _this._defaultModel = newMeshes[1];
  65596. _this.attachToMesh(_this._defaultModel);
  65597. if (meshLoaded) {
  65598. meshLoaded(_this._defaultModel);
  65599. }
  65600. });
  65601. };
  65602. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  65603. // helper getters for left and right hand.
  65604. get: function () {
  65605. if (this.hand === 'right') {
  65606. return this.onMainButtonStateChangedObservable;
  65607. }
  65608. else {
  65609. throw new Error('No A button on left hand');
  65610. }
  65611. },
  65612. enumerable: true,
  65613. configurable: true
  65614. });
  65615. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  65616. get: function () {
  65617. if (this.hand === 'right') {
  65618. return this.onSecondaryButtonStateChangedObservable;
  65619. }
  65620. else {
  65621. throw new Error('No B button on left hand');
  65622. }
  65623. },
  65624. enumerable: true,
  65625. configurable: true
  65626. });
  65627. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  65628. get: function () {
  65629. if (this.hand === 'left') {
  65630. return this.onMainButtonStateChangedObservable;
  65631. }
  65632. else {
  65633. throw new Error('No X button on right hand');
  65634. }
  65635. },
  65636. enumerable: true,
  65637. configurable: true
  65638. });
  65639. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  65640. get: function () {
  65641. if (this.hand === 'left') {
  65642. return this.onSecondaryButtonStateChangedObservable;
  65643. }
  65644. else {
  65645. throw new Error('No Y button on right hand');
  65646. }
  65647. },
  65648. enumerable: true,
  65649. configurable: true
  65650. });
  65651. /*
  65652. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  65653. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  65654. 2) secondary trigger (same)
  65655. 3) A (right) X (left), touch, pressed = value
  65656. 4) B / Y
  65657. 5) thumb rest
  65658. */
  65659. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65660. var notifyObject = state; //{ state: state, changes: changes };
  65661. var triggerDirection = this.hand === 'right' ? -1 : 1;
  65662. switch (buttonIdx) {
  65663. case 0:
  65664. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65665. return;
  65666. case 1:// index trigger
  65667. if (this._defaultModel) {
  65668. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  65669. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  65670. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  65671. }
  65672. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65673. return;
  65674. case 2:// secondary trigger
  65675. if (this._defaultModel) {
  65676. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  65677. }
  65678. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  65679. return;
  65680. case 3:
  65681. if (this._defaultModel) {
  65682. if (notifyObject.pressed) {
  65683. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65684. }
  65685. else {
  65686. (this._defaultModel.getChildren()[1]).position.y = 0;
  65687. }
  65688. }
  65689. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65690. return;
  65691. case 4:
  65692. if (this._defaultModel) {
  65693. if (notifyObject.pressed) {
  65694. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65695. }
  65696. else {
  65697. (this._defaultModel.getChildren()[2]).position.y = 0;
  65698. }
  65699. }
  65700. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65701. return;
  65702. case 5:
  65703. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65704. return;
  65705. }
  65706. };
  65707. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65708. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65709. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65710. return OculusTouchController;
  65711. }(BABYLON.WebVRController));
  65712. BABYLON.OculusTouchController = OculusTouchController;
  65713. })(BABYLON || (BABYLON = {}));
  65714. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65715. var BABYLON;
  65716. (function (BABYLON) {
  65717. var ViveController = /** @class */ (function (_super) {
  65718. __extends(ViveController, _super);
  65719. function ViveController(vrGamepad) {
  65720. var _this = _super.call(this, vrGamepad) || this;
  65721. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65722. _this._invertLeftStickY = true;
  65723. return _this;
  65724. }
  65725. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65726. var _this = this;
  65727. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65728. /*
  65729. Parent Mesh name: ViveWand
  65730. - body
  65731. - r_gripper
  65732. - l_gripper
  65733. - menu_button
  65734. - system_button
  65735. - trackpad
  65736. - trigger
  65737. - LED
  65738. */
  65739. _this._defaultModel = newMeshes[1];
  65740. _this.attachToMesh(_this._defaultModel);
  65741. if (meshLoaded) {
  65742. meshLoaded(_this._defaultModel);
  65743. }
  65744. });
  65745. };
  65746. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65747. get: function () {
  65748. return this.onMainButtonStateChangedObservable;
  65749. },
  65750. enumerable: true,
  65751. configurable: true
  65752. });
  65753. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65754. get: function () {
  65755. return this.onMainButtonStateChangedObservable;
  65756. },
  65757. enumerable: true,
  65758. configurable: true
  65759. });
  65760. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65761. get: function () {
  65762. return this.onSecondaryButtonStateChangedObservable;
  65763. },
  65764. enumerable: true,
  65765. configurable: true
  65766. });
  65767. /**
  65768. * Vive mapping:
  65769. * 0: touchpad
  65770. * 1: trigger
  65771. * 2: left AND right buttons
  65772. * 3: menu button
  65773. */
  65774. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65775. var notifyObject = state; //{ state: state, changes: changes };
  65776. switch (buttonIdx) {
  65777. case 0:
  65778. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65779. return;
  65780. case 1:// index trigger
  65781. if (this._defaultModel) {
  65782. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  65783. }
  65784. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65785. return;
  65786. case 2:// left AND right button
  65787. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65788. return;
  65789. case 3:
  65790. if (this._defaultModel) {
  65791. if (notifyObject.pressed) {
  65792. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65793. }
  65794. else {
  65795. (this._defaultModel.getChildren()[2]).position.y = 0;
  65796. }
  65797. }
  65798. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65799. return;
  65800. }
  65801. };
  65802. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  65803. ViveController.MODEL_FILENAME = 'wand.babylon';
  65804. return ViveController;
  65805. }(BABYLON.WebVRController));
  65806. BABYLON.ViveController = ViveController;
  65807. })(BABYLON || (BABYLON = {}));
  65808. //# sourceMappingURL=babylon.viveController.js.map
  65809. var BABYLON;
  65810. (function (BABYLON) {
  65811. var GenericController = /** @class */ (function (_super) {
  65812. __extends(GenericController, _super);
  65813. function GenericController(vrGamepad) {
  65814. return _super.call(this, vrGamepad) || this;
  65815. }
  65816. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65817. var _this = this;
  65818. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  65819. _this._defaultModel = newMeshes[1];
  65820. _this.attachToMesh(_this._defaultModel);
  65821. if (meshLoaded) {
  65822. meshLoaded(_this._defaultModel);
  65823. }
  65824. });
  65825. };
  65826. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65827. console.log("Button id: " + buttonIdx + "state: ");
  65828. console.dir(state);
  65829. };
  65830. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65831. GenericController.MODEL_FILENAME = 'generic.babylon';
  65832. return GenericController;
  65833. }(BABYLON.WebVRController));
  65834. BABYLON.GenericController = GenericController;
  65835. })(BABYLON || (BABYLON = {}));
  65836. //# sourceMappingURL=babylon.genericController.js.map
  65837. var BABYLON;
  65838. (function (BABYLON) {
  65839. var LoadedMeshInfo = /** @class */ (function () {
  65840. function LoadedMeshInfo() {
  65841. this.buttonMeshes = {};
  65842. this.axisMeshes = {};
  65843. }
  65844. return LoadedMeshInfo;
  65845. }());
  65846. var WindowsMotionController = /** @class */ (function (_super) {
  65847. __extends(WindowsMotionController, _super);
  65848. function WindowsMotionController(vrGamepad) {
  65849. var _this = _super.call(this, vrGamepad) || this;
  65850. _this._mapping = {
  65851. // Semantic button names
  65852. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65853. // A mapping of the button name to glTF model node name
  65854. // that should be transformed by button value.
  65855. buttonMeshNames: {
  65856. 'trigger': 'SELECT',
  65857. 'menu': 'MENU',
  65858. 'grip': 'GRASP',
  65859. 'thumbstick': 'THUMBSTICK_PRESS',
  65860. 'trackpad': 'TOUCHPAD_PRESS'
  65861. },
  65862. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65863. buttonObservableNames: {
  65864. 'trigger': 'onTriggerStateChangedObservable',
  65865. 'menu': 'onSecondaryButtonStateChangedObservable',
  65866. 'grip': 'onMainButtonStateChangedObservable',
  65867. 'thumbstick': 'onPadStateChangedObservable',
  65868. 'trackpad': 'onTrackpadChangedObservable'
  65869. },
  65870. // A mapping of the axis name to glTF model node name
  65871. // that should be transformed by axis value.
  65872. // This array mirrors the browserGamepad.axes array, such that
  65873. // the mesh corresponding to axis 0 is in this array index 0.
  65874. axisMeshNames: [
  65875. 'THUMBSTICK_X',
  65876. 'THUMBSTICK_Y',
  65877. 'TOUCHPAD_TOUCH_X',
  65878. 'TOUCHPAD_TOUCH_Y'
  65879. ],
  65880. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  65881. };
  65882. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  65883. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  65884. _this.trackpad = { x: 0, y: 0 };
  65885. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  65886. _this._loadedMeshInfo = null;
  65887. return _this;
  65888. }
  65889. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  65890. get: function () {
  65891. return this.onTriggerStateChangedObservable;
  65892. },
  65893. enumerable: true,
  65894. configurable: true
  65895. });
  65896. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  65897. get: function () {
  65898. return this.onSecondaryButtonStateChangedObservable;
  65899. },
  65900. enumerable: true,
  65901. configurable: true
  65902. });
  65903. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  65904. get: function () {
  65905. return this.onMainButtonStateChangedObservable;
  65906. },
  65907. enumerable: true,
  65908. configurable: true
  65909. });
  65910. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65911. get: function () {
  65912. return this.onPadStateChangedObservable;
  65913. },
  65914. enumerable: true,
  65915. configurable: true
  65916. });
  65917. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65918. get: function () {
  65919. return this.onTrackpadChangedObservable;
  65920. },
  65921. enumerable: true,
  65922. configurable: true
  65923. });
  65924. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65925. get: function () {
  65926. return this.onTrackpadValuesChangedObservable;
  65927. },
  65928. enumerable: true,
  65929. configurable: true
  65930. });
  65931. /**
  65932. * Called once per frame by the engine.
  65933. */
  65934. WindowsMotionController.prototype.update = function () {
  65935. _super.prototype.update.call(this);
  65936. if (this.browserGamepad.axes) {
  65937. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65938. this.trackpad.x = this.browserGamepad["axes"][2];
  65939. this.trackpad.y = this.browserGamepad["axes"][3];
  65940. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65941. }
  65942. // Only need to animate axes if there is a loaded mesh
  65943. if (this._loadedMeshInfo) {
  65944. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65945. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65946. }
  65947. }
  65948. }
  65949. };
  65950. /**
  65951. * Called once for each button that changed state since the last frame
  65952. * @param buttonIdx Which button index changed
  65953. * @param state New state of the button
  65954. * @param changes Which properties on the state changed since last frame
  65955. */
  65956. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65957. var buttonName = this._mapping.buttons[buttonIdx];
  65958. if (!buttonName) {
  65959. return;
  65960. }
  65961. // Only emit events for buttons that we know how to map from index to name
  65962. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65963. if (observable) {
  65964. observable.notifyObservers(state);
  65965. }
  65966. this.lerpButtonTransform(buttonName, state.value);
  65967. };
  65968. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65969. // If there is no loaded mesh, there is nothing to transform.
  65970. if (!this._loadedMeshInfo) {
  65971. return;
  65972. }
  65973. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65974. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65975. return;
  65976. }
  65977. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65978. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65979. };
  65980. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65981. if (!this._loadedMeshInfo) {
  65982. return;
  65983. }
  65984. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65985. if (!meshInfo) {
  65986. return;
  65987. }
  65988. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65989. return;
  65990. }
  65991. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65992. var lerpValue = axisValue * 0.5 + 0.5;
  65993. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65994. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65995. };
  65996. /**
  65997. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65998. * @param scene scene in which to add meshes
  65999. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  66000. */
  66001. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  66002. var _this = this;
  66003. if (forceDefault === void 0) { forceDefault = false; }
  66004. var path;
  66005. var filename;
  66006. // Checking if GLB loader is present
  66007. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  66008. // Determine the device specific folder based on the ID suffix
  66009. var device = 'default';
  66010. if (this.id && !forceDefault) {
  66011. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  66012. device = ((match && match[0]) || device);
  66013. }
  66014. // Hand
  66015. if (this.hand === 'left') {
  66016. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  66017. }
  66018. else {
  66019. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  66020. }
  66021. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  66022. }
  66023. else {
  66024. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  66025. path = BABYLON.GenericController.MODEL_BASE_URL;
  66026. filename = BABYLON.GenericController.MODEL_FILENAME;
  66027. }
  66028. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  66029. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  66030. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  66031. if (!_this._loadedMeshInfo) {
  66032. return;
  66033. }
  66034. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  66035. _this.attachToMesh(_this._defaultModel);
  66036. if (meshLoaded) {
  66037. meshLoaded(_this._defaultModel);
  66038. }
  66039. }, null, function (scene, message) {
  66040. BABYLON.Tools.Log(message);
  66041. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  66042. if (!forceDefault) {
  66043. _this.initControllerMesh(scene, meshLoaded, true);
  66044. }
  66045. });
  66046. };
  66047. /**
  66048. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  66049. * can be transformed by button presses and axes values, based on this._mapping.
  66050. *
  66051. * @param scene scene in which the meshes exist
  66052. * @param meshes list of meshes that make up the controller model to process
  66053. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  66054. */
  66055. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  66056. var loadedMeshInfo = null;
  66057. // Create a new mesh to contain the glTF hierarchy
  66058. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  66059. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  66060. var childMesh = null;
  66061. for (var i = 0; i < meshes.length; i++) {
  66062. var mesh = meshes[i];
  66063. if (!mesh.parent) {
  66064. // Exclude controller meshes from picking results
  66065. mesh.isPickable = false;
  66066. // Handle root node, attach to the new parentMesh
  66067. childMesh = mesh;
  66068. break;
  66069. }
  66070. }
  66071. if (childMesh) {
  66072. childMesh.setParent(parentMesh);
  66073. // Create our mesh info. Note that this method will always return non-null.
  66074. loadedMeshInfo = this.createMeshInfo(parentMesh);
  66075. }
  66076. else {
  66077. BABYLON.Tools.Warn('Could not find root node in model file.');
  66078. }
  66079. return loadedMeshInfo;
  66080. };
  66081. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  66082. var loadedMeshInfo = new LoadedMeshInfo();
  66083. var i;
  66084. loadedMeshInfo.rootNode = rootNode;
  66085. // Reset the caches
  66086. loadedMeshInfo.buttonMeshes = {};
  66087. loadedMeshInfo.axisMeshes = {};
  66088. // Button Meshes
  66089. for (i = 0; i < this._mapping.buttons.length; i++) {
  66090. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  66091. if (!buttonMeshName) {
  66092. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  66093. continue;
  66094. }
  66095. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  66096. if (!buttonMesh) {
  66097. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  66098. continue;
  66099. }
  66100. var buttonMeshInfo = {
  66101. index: i,
  66102. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  66103. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  66104. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  66105. };
  66106. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  66107. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  66108. }
  66109. else {
  66110. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  66111. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  66112. '(VALUE: ' + !!buttonMeshInfo.value +
  66113. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  66114. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  66115. ')');
  66116. }
  66117. }
  66118. // Axis Meshes
  66119. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  66120. var axisMeshName = this._mapping.axisMeshNames[i];
  66121. if (!axisMeshName) {
  66122. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  66123. continue;
  66124. }
  66125. var axisMesh = getChildByName(rootNode, axisMeshName);
  66126. if (!axisMesh) {
  66127. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  66128. continue;
  66129. }
  66130. var axisMeshInfo = {
  66131. index: i,
  66132. value: getImmediateChildByName(axisMesh, 'VALUE'),
  66133. min: getImmediateChildByName(axisMesh, 'MIN'),
  66134. max: getImmediateChildByName(axisMesh, 'MAX')
  66135. };
  66136. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  66137. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  66138. }
  66139. else {
  66140. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  66141. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  66142. '(VALUE: ' + !!axisMeshInfo.value +
  66143. ', MIN: ' + !!axisMeshInfo.min +
  66144. ', MAX:' + !!axisMeshInfo.max +
  66145. ')');
  66146. }
  66147. }
  66148. // Pointing Ray
  66149. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  66150. if (!loadedMeshInfo.pointingPoseNode) {
  66151. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  66152. }
  66153. return loadedMeshInfo;
  66154. // Look through all children recursively. This will return null if no mesh exists with the given name.
  66155. function getChildByName(node, name) {
  66156. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  66157. }
  66158. // Look through only immediate children. This will return null if no mesh exists with the given name.
  66159. function getImmediateChildByName(node, name) {
  66160. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  66161. }
  66162. };
  66163. WindowsMotionController.prototype.getForwardRay = function (length) {
  66164. if (length === void 0) { length = 100; }
  66165. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  66166. return _super.prototype.getForwardRay.call(this, length);
  66167. }
  66168. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  66169. var origin = m.getTranslation();
  66170. var forward = new BABYLON.Vector3(0, 0, -1);
  66171. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66172. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66173. return new BABYLON.Ray(origin, direction, length);
  66174. };
  66175. WindowsMotionController.prototype.dispose = function () {
  66176. _super.prototype.dispose.call(this);
  66177. this.onTrackpadChangedObservable.clear();
  66178. };
  66179. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  66180. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  66181. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  66182. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  66183. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  66184. return WindowsMotionController;
  66185. }(BABYLON.WebVRController));
  66186. BABYLON.WindowsMotionController = WindowsMotionController;
  66187. })(BABYLON || (BABYLON = {}));
  66188. //# sourceMappingURL=babylon.windowsMotionController.js.map
  66189. var BABYLON;
  66190. (function (BABYLON) {
  66191. var GearVRController = /** @class */ (function (_super) {
  66192. __extends(GearVRController, _super);
  66193. function GearVRController(vrGamepad) {
  66194. var _this = _super.call(this, vrGamepad) || this;
  66195. _this._buttonIndexToObservableNameMap = [
  66196. 'onTrackpadChangedObservable',
  66197. 'onTriggerStateChangedObservable' // Trigger
  66198. ];
  66199. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  66200. return _this;
  66201. }
  66202. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66203. var _this = this;
  66204. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  66205. _this._defaultModel = newMeshes[1];
  66206. _this.attachToMesh(_this._defaultModel);
  66207. if (meshLoaded) {
  66208. meshLoaded(_this._defaultModel);
  66209. }
  66210. });
  66211. };
  66212. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66213. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  66214. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  66215. // Only emit events for buttons that we know how to map from index to observable
  66216. var observable = this[observableName];
  66217. if (observable) {
  66218. observable.notifyObservers(state);
  66219. }
  66220. }
  66221. };
  66222. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66223. GearVRController.MODEL_FILENAME = 'generic.babylon';
  66224. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  66225. return GearVRController;
  66226. }(BABYLON.WebVRController));
  66227. BABYLON.GearVRController = GearVRController;
  66228. })(BABYLON || (BABYLON = {}));
  66229. //# sourceMappingURL=babylon.gearVRController.js.map
  66230. var BABYLON;
  66231. (function (BABYLON) {
  66232. /**
  66233. * Google Daydream controller
  66234. */
  66235. var DaydreamController = /** @class */ (function (_super) {
  66236. __extends(DaydreamController, _super);
  66237. function DaydreamController(vrGamepad) {
  66238. var _this = _super.call(this, vrGamepad) || this;
  66239. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  66240. return _this;
  66241. }
  66242. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66243. var _this = this;
  66244. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  66245. _this._defaultModel = newMeshes[1];
  66246. _this.attachToMesh(_this._defaultModel);
  66247. if (meshLoaded) {
  66248. meshLoaded(_this._defaultModel);
  66249. }
  66250. });
  66251. };
  66252. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66253. // Daydream controller only has 1 GamepadButton (on the trackpad).
  66254. if (buttonIdx === 0) {
  66255. var observable = this.onTriggerStateChangedObservable;
  66256. if (observable) {
  66257. observable.notifyObservers(state);
  66258. }
  66259. }
  66260. else {
  66261. // If the app or home buttons are ever made available
  66262. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  66263. }
  66264. };
  66265. /**
  66266. * Base Url for the controller model.
  66267. */
  66268. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66269. /**
  66270. * File name for the controller model.
  66271. */
  66272. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  66273. /**
  66274. * Gamepad Id prefix used to identify Daydream Controller.
  66275. */
  66276. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  66277. return DaydreamController;
  66278. }(BABYLON.WebVRController));
  66279. BABYLON.DaydreamController = DaydreamController;
  66280. })(BABYLON || (BABYLON = {}));
  66281. //# sourceMappingURL=babylon.daydreamController.js.map
  66282. var BABYLON;
  66283. (function (BABYLON) {
  66284. var FollowCamera = /** @class */ (function (_super) {
  66285. __extends(FollowCamera, _super);
  66286. function FollowCamera(name, position, scene, lockedTarget) {
  66287. if (lockedTarget === void 0) { lockedTarget = null; }
  66288. var _this = _super.call(this, name, position, scene) || this;
  66289. _this.radius = 12;
  66290. _this.rotationOffset = 0;
  66291. _this.heightOffset = 4;
  66292. _this.cameraAcceleration = 0.05;
  66293. _this.maxCameraSpeed = 20;
  66294. _this.lockedTarget = lockedTarget;
  66295. return _this;
  66296. }
  66297. FollowCamera.prototype.getRadians = function (degrees) {
  66298. return degrees * Math.PI / 180;
  66299. };
  66300. FollowCamera.prototype.follow = function (cameraTarget) {
  66301. if (!cameraTarget)
  66302. return;
  66303. var yRotation;
  66304. if (cameraTarget.rotationQuaternion) {
  66305. var rotMatrix = new BABYLON.Matrix();
  66306. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  66307. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  66308. }
  66309. else {
  66310. yRotation = cameraTarget.rotation.y;
  66311. }
  66312. var radians = this.getRadians(this.rotationOffset) + yRotation;
  66313. var targetPosition = cameraTarget.getAbsolutePosition();
  66314. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  66315. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  66316. var dx = targetX - this.position.x;
  66317. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  66318. var dz = (targetZ) - this.position.z;
  66319. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  66320. var vy = dy * this.cameraAcceleration;
  66321. var vz = dz * this.cameraAcceleration * 2;
  66322. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  66323. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66324. }
  66325. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  66326. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66327. }
  66328. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  66329. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66330. }
  66331. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  66332. this.setTarget(targetPosition);
  66333. };
  66334. FollowCamera.prototype._checkInputs = function () {
  66335. _super.prototype._checkInputs.call(this);
  66336. if (this.lockedTarget) {
  66337. this.follow(this.lockedTarget);
  66338. }
  66339. };
  66340. FollowCamera.prototype.getClassName = function () {
  66341. return "FollowCamera";
  66342. };
  66343. __decorate([
  66344. BABYLON.serialize()
  66345. ], FollowCamera.prototype, "radius", void 0);
  66346. __decorate([
  66347. BABYLON.serialize()
  66348. ], FollowCamera.prototype, "rotationOffset", void 0);
  66349. __decorate([
  66350. BABYLON.serialize()
  66351. ], FollowCamera.prototype, "heightOffset", void 0);
  66352. __decorate([
  66353. BABYLON.serialize()
  66354. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  66355. __decorate([
  66356. BABYLON.serialize()
  66357. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  66358. __decorate([
  66359. BABYLON.serializeAsMeshReference("lockedTargetId")
  66360. ], FollowCamera.prototype, "lockedTarget", void 0);
  66361. return FollowCamera;
  66362. }(BABYLON.TargetCamera));
  66363. BABYLON.FollowCamera = FollowCamera;
  66364. var ArcFollowCamera = /** @class */ (function (_super) {
  66365. __extends(ArcFollowCamera, _super);
  66366. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  66367. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  66368. _this.alpha = alpha;
  66369. _this.beta = beta;
  66370. _this.radius = radius;
  66371. _this.target = target;
  66372. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  66373. _this.follow();
  66374. return _this;
  66375. }
  66376. ArcFollowCamera.prototype.follow = function () {
  66377. if (!this.target) {
  66378. return;
  66379. }
  66380. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  66381. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  66382. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  66383. var targetPosition = this.target.getAbsolutePosition();
  66384. this.position = targetPosition.add(this._cartesianCoordinates);
  66385. this.setTarget(targetPosition);
  66386. };
  66387. ArcFollowCamera.prototype._checkInputs = function () {
  66388. _super.prototype._checkInputs.call(this);
  66389. this.follow();
  66390. };
  66391. ArcFollowCamera.prototype.getClassName = function () {
  66392. return "ArcFollowCamera";
  66393. };
  66394. return ArcFollowCamera;
  66395. }(BABYLON.TargetCamera));
  66396. BABYLON.ArcFollowCamera = ArcFollowCamera;
  66397. })(BABYLON || (BABYLON = {}));
  66398. //# sourceMappingURL=babylon.followCamera.js.map
  66399. var BABYLON;
  66400. (function (BABYLON) {
  66401. // We're mainly based on the logic defined into the FreeCamera code
  66402. var UniversalCamera = /** @class */ (function (_super) {
  66403. __extends(UniversalCamera, _super);
  66404. //-- end properties for backward compatibility for inputs
  66405. function UniversalCamera(name, position, scene) {
  66406. var _this = _super.call(this, name, position, scene) || this;
  66407. _this.inputs.addGamepad();
  66408. return _this;
  66409. }
  66410. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  66411. //-- Begin properties for backward compatibility for inputs
  66412. get: function () {
  66413. var gamepad = this.inputs.attached["gamepad"];
  66414. if (gamepad)
  66415. return gamepad.gamepadAngularSensibility;
  66416. return 0;
  66417. },
  66418. set: function (value) {
  66419. var gamepad = this.inputs.attached["gamepad"];
  66420. if (gamepad)
  66421. gamepad.gamepadAngularSensibility = value;
  66422. },
  66423. enumerable: true,
  66424. configurable: true
  66425. });
  66426. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  66427. get: function () {
  66428. var gamepad = this.inputs.attached["gamepad"];
  66429. if (gamepad)
  66430. return gamepad.gamepadMoveSensibility;
  66431. return 0;
  66432. },
  66433. set: function (value) {
  66434. var gamepad = this.inputs.attached["gamepad"];
  66435. if (gamepad)
  66436. gamepad.gamepadMoveSensibility = value;
  66437. },
  66438. enumerable: true,
  66439. configurable: true
  66440. });
  66441. UniversalCamera.prototype.getClassName = function () {
  66442. return "UniversalCamera";
  66443. };
  66444. return UniversalCamera;
  66445. }(BABYLON.TouchCamera));
  66446. BABYLON.UniversalCamera = UniversalCamera;
  66447. })(BABYLON || (BABYLON = {}));
  66448. //# sourceMappingURL=babylon.universalCamera.js.map
  66449. var BABYLON;
  66450. (function (BABYLON) {
  66451. // We're mainly based on the logic defined into the FreeCamera code
  66452. var GamepadCamera = /** @class */ (function (_super) {
  66453. __extends(GamepadCamera, _super);
  66454. //-- end properties for backward compatibility for inputs
  66455. function GamepadCamera(name, position, scene) {
  66456. return _super.call(this, name, position, scene) || this;
  66457. }
  66458. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  66459. //-- Begin properties for backward compatibility for inputs
  66460. get: function () {
  66461. var gamepad = this.inputs.attached["gamepad"];
  66462. if (gamepad)
  66463. return gamepad.gamepadAngularSensibility;
  66464. return 0;
  66465. },
  66466. set: function (value) {
  66467. var gamepad = this.inputs.attached["gamepad"];
  66468. if (gamepad)
  66469. gamepad.gamepadAngularSensibility = value;
  66470. },
  66471. enumerable: true,
  66472. configurable: true
  66473. });
  66474. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  66475. get: function () {
  66476. var gamepad = this.inputs.attached["gamepad"];
  66477. if (gamepad)
  66478. return gamepad.gamepadMoveSensibility;
  66479. return 0;
  66480. },
  66481. set: function (value) {
  66482. var gamepad = this.inputs.attached["gamepad"];
  66483. if (gamepad)
  66484. gamepad.gamepadMoveSensibility = value;
  66485. },
  66486. enumerable: true,
  66487. configurable: true
  66488. });
  66489. GamepadCamera.prototype.getClassName = function () {
  66490. return "GamepadCamera";
  66491. };
  66492. return GamepadCamera;
  66493. }(BABYLON.UniversalCamera));
  66494. BABYLON.GamepadCamera = GamepadCamera;
  66495. })(BABYLON || (BABYLON = {}));
  66496. //# sourceMappingURL=babylon.gamepadCamera.js.map
  66497. var BABYLON;
  66498. (function (BABYLON) {
  66499. var PostProcessRenderPipelineManager = /** @class */ (function () {
  66500. function PostProcessRenderPipelineManager() {
  66501. this._renderPipelines = {};
  66502. }
  66503. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  66504. this._renderPipelines[renderPipeline._name] = renderPipeline;
  66505. };
  66506. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  66507. if (unique === void 0) { unique = false; }
  66508. var renderPipeline = this._renderPipelines[renderPipelineName];
  66509. if (!renderPipeline) {
  66510. return;
  66511. }
  66512. renderPipeline._attachCameras(cameras, unique);
  66513. };
  66514. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  66515. var renderPipeline = this._renderPipelines[renderPipelineName];
  66516. if (!renderPipeline) {
  66517. return;
  66518. }
  66519. renderPipeline._detachCameras(cameras);
  66520. };
  66521. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66522. var renderPipeline = this._renderPipelines[renderPipelineName];
  66523. if (!renderPipeline) {
  66524. return;
  66525. }
  66526. renderPipeline._enableEffect(renderEffectName, cameras);
  66527. };
  66528. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66529. var renderPipeline = this._renderPipelines[renderPipelineName];
  66530. if (!renderPipeline) {
  66531. return;
  66532. }
  66533. renderPipeline._disableEffect(renderEffectName, cameras);
  66534. };
  66535. PostProcessRenderPipelineManager.prototype.update = function () {
  66536. for (var renderPipelineName in this._renderPipelines) {
  66537. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66538. var pipeline = this._renderPipelines[renderPipelineName];
  66539. if (!pipeline.isSupported) {
  66540. pipeline.dispose();
  66541. delete this._renderPipelines[renderPipelineName];
  66542. }
  66543. else {
  66544. pipeline._update();
  66545. }
  66546. }
  66547. }
  66548. };
  66549. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  66550. for (var renderPipelineName in this._renderPipelines) {
  66551. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66552. var pipeline = this._renderPipelines[renderPipelineName];
  66553. pipeline._rebuild();
  66554. }
  66555. }
  66556. };
  66557. PostProcessRenderPipelineManager.prototype.dispose = function () {
  66558. for (var renderPipelineName in this._renderPipelines) {
  66559. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66560. var pipeline = this._renderPipelines[renderPipelineName];
  66561. pipeline.dispose();
  66562. }
  66563. }
  66564. };
  66565. return PostProcessRenderPipelineManager;
  66566. }());
  66567. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  66568. })(BABYLON || (BABYLON = {}));
  66569. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  66570. var BABYLON;
  66571. (function (BABYLON) {
  66572. /**
  66573. * This represents a set of one or more post processes in Babylon.
  66574. * A post process can be used to apply a shader to a texture after it is rendered.
  66575. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  66576. */
  66577. var PostProcessRenderEffect = /** @class */ (function () {
  66578. /**
  66579. * Instantiates a post process render effect.
  66580. * A post process can be used to apply a shader to a texture after it is rendered.
  66581. * @param engine The engine the effect is tied to
  66582. * @param name The name of the effect
  66583. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  66584. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  66585. */
  66586. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  66587. this._name = name;
  66588. this._singleInstance = singleInstance || true;
  66589. this._getPostProcesses = getPostProcesses;
  66590. this._cameras = {};
  66591. this._indicesForCamera = {};
  66592. this._postProcesses = {};
  66593. }
  66594. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  66595. /**
  66596. * Checks if all the post processes in the effect are supported.
  66597. */
  66598. get: function () {
  66599. for (var index in this._postProcesses) {
  66600. for (var ppIndex in this._postProcesses[index]) {
  66601. if (!this._postProcesses[index][ppIndex].isSupported) {
  66602. return false;
  66603. }
  66604. }
  66605. }
  66606. return true;
  66607. },
  66608. enumerable: true,
  66609. configurable: true
  66610. });
  66611. /**
  66612. * Updates the current state of the effect
  66613. */
  66614. PostProcessRenderEffect.prototype._update = function () {
  66615. };
  66616. /**
  66617. * Attaches the effect on cameras
  66618. * @param cameras The camera to attach to.
  66619. */
  66620. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  66621. var _this = this;
  66622. var cameraKey;
  66623. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66624. if (!cams) {
  66625. return;
  66626. }
  66627. for (var i = 0; i < cams.length; i++) {
  66628. var camera = cams[i];
  66629. var cameraName = camera.name;
  66630. if (this._singleInstance) {
  66631. cameraKey = 0;
  66632. }
  66633. else {
  66634. cameraKey = cameraName;
  66635. }
  66636. if (!this._postProcesses[cameraKey]) {
  66637. var postProcess = this._getPostProcesses();
  66638. if (postProcess) {
  66639. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  66640. }
  66641. }
  66642. if (!this._indicesForCamera[cameraName]) {
  66643. this._indicesForCamera[cameraName] = [];
  66644. }
  66645. this._postProcesses[cameraKey].forEach(function (postProcess) {
  66646. var index = camera.attachPostProcess(postProcess);
  66647. _this._indicesForCamera[cameraName].push(index);
  66648. });
  66649. if (!this._cameras[cameraName]) {
  66650. this._cameras[cameraName] = camera;
  66651. }
  66652. }
  66653. };
  66654. /**
  66655. * Detatches the effect on cameras
  66656. * @param cameras The camera to detatch from.
  66657. */
  66658. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  66659. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66660. if (!cams) {
  66661. return;
  66662. }
  66663. for (var i = 0; i < cams.length; i++) {
  66664. var camera = cams[i];
  66665. var cameraName = camera.name;
  66666. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66667. camera.detachPostProcess(postProcess);
  66668. });
  66669. if (this._cameras[cameraName]) {
  66670. //this._indicesForCamera.splice(index, 1);
  66671. this._cameras[cameraName] = null;
  66672. }
  66673. }
  66674. };
  66675. /**
  66676. * Enables the effect on given cameras
  66677. * @param cameras The camera to enable.
  66678. */
  66679. PostProcessRenderEffect.prototype._enable = function (cameras) {
  66680. var _this = this;
  66681. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66682. if (!cams) {
  66683. return;
  66684. }
  66685. for (var i = 0; i < cams.length; i++) {
  66686. var camera = cams[i];
  66687. var cameraName = camera.name;
  66688. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66689. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  66690. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66691. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66692. });
  66693. }
  66694. }
  66695. }
  66696. };
  66697. /**
  66698. * Disables the effect on the given cameras
  66699. * @param cameras The camera to disable.
  66700. */
  66701. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66702. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66703. if (!cams) {
  66704. return;
  66705. }
  66706. for (var i = 0; i < cams.length; i++) {
  66707. var camera = cams[i];
  66708. var cameraName = camera.name;
  66709. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66710. camera.detachPostProcess(postProcess);
  66711. });
  66712. }
  66713. };
  66714. /**
  66715. * Gets a list of the post processes contained in the effect.
  66716. * @param camera The camera to get the post processes on.
  66717. * @returns The list of the post processes in the effect.
  66718. */
  66719. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66720. if (this._singleInstance) {
  66721. return this._postProcesses[0];
  66722. }
  66723. else {
  66724. if (!camera) {
  66725. return null;
  66726. }
  66727. return this._postProcesses[camera.name];
  66728. }
  66729. };
  66730. return PostProcessRenderEffect;
  66731. }());
  66732. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66733. })(BABYLON || (BABYLON = {}));
  66734. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66735. var BABYLON;
  66736. (function (BABYLON) {
  66737. var PostProcessRenderPipeline = /** @class */ (function () {
  66738. function PostProcessRenderPipeline(engine, name) {
  66739. this.engine = engine;
  66740. this._name = name;
  66741. this._renderEffects = {};
  66742. this._renderEffectsForIsolatedPass = new Array();
  66743. this._cameras = [];
  66744. }
  66745. PostProcessRenderPipeline.prototype.getClassName = function () {
  66746. return "PostProcessRenderPipeline";
  66747. };
  66748. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66749. get: function () {
  66750. for (var renderEffectName in this._renderEffects) {
  66751. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66752. if (!this._renderEffects[renderEffectName].isSupported) {
  66753. return false;
  66754. }
  66755. }
  66756. }
  66757. return true;
  66758. },
  66759. enumerable: true,
  66760. configurable: true
  66761. });
  66762. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66763. this._renderEffects[renderEffect._name] = renderEffect;
  66764. };
  66765. // private
  66766. PostProcessRenderPipeline.prototype._rebuild = function () {
  66767. };
  66768. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  66769. var renderEffects = this._renderEffects[renderEffectName];
  66770. if (!renderEffects) {
  66771. return;
  66772. }
  66773. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66774. };
  66775. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  66776. var renderEffects = this._renderEffects[renderEffectName];
  66777. if (!renderEffects) {
  66778. return;
  66779. }
  66780. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66781. };
  66782. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  66783. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66784. if (!cams) {
  66785. return;
  66786. }
  66787. var indicesToDelete = [];
  66788. var i;
  66789. for (i = 0; i < cams.length; i++) {
  66790. var camera = cams[i];
  66791. var cameraName = camera.name;
  66792. if (this._cameras.indexOf(camera) === -1) {
  66793. this._cameras[cameraName] = camera;
  66794. }
  66795. else if (unique) {
  66796. indicesToDelete.push(i);
  66797. }
  66798. }
  66799. for (i = 0; i < indicesToDelete.length; i++) {
  66800. cameras.splice(indicesToDelete[i], 1);
  66801. }
  66802. for (var renderEffectName in this._renderEffects) {
  66803. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66804. this._renderEffects[renderEffectName]._attachCameras(cams);
  66805. }
  66806. }
  66807. };
  66808. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  66809. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66810. if (!cams) {
  66811. return;
  66812. }
  66813. for (var renderEffectName in this._renderEffects) {
  66814. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66815. this._renderEffects[renderEffectName]._detachCameras(cams);
  66816. }
  66817. }
  66818. for (var i = 0; i < cams.length; i++) {
  66819. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  66820. }
  66821. };
  66822. PostProcessRenderPipeline.prototype._update = function () {
  66823. for (var renderEffectName in this._renderEffects) {
  66824. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66825. this._renderEffects[renderEffectName]._update();
  66826. }
  66827. }
  66828. for (var i = 0; i < this._cameras.length; i++) {
  66829. var cameraName = this._cameras[i].name;
  66830. if (this._renderEffectsForIsolatedPass[cameraName]) {
  66831. this._renderEffectsForIsolatedPass[cameraName]._update();
  66832. }
  66833. }
  66834. };
  66835. PostProcessRenderPipeline.prototype._reset = function () {
  66836. this._renderEffects = {};
  66837. this._renderEffectsForIsolatedPass = new Array();
  66838. };
  66839. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  66840. // 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)
  66841. var effectKeys = Object.keys(this._renderEffects);
  66842. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  66843. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  66844. if (postProcesses) {
  66845. postProcesses[0].samples = 4;
  66846. return true;
  66847. }
  66848. }
  66849. return false;
  66850. };
  66851. PostProcessRenderPipeline.prototype.dispose = function () {
  66852. // Must be implemented by children
  66853. };
  66854. __decorate([
  66855. BABYLON.serialize()
  66856. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66857. return PostProcessRenderPipeline;
  66858. }());
  66859. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66860. })(BABYLON || (BABYLON = {}));
  66861. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66862. var BABYLON;
  66863. (function (BABYLON) {
  66864. /**
  66865. * This represents a depth renderer in Babylon.
  66866. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66867. */
  66868. var DepthRenderer = /** @class */ (function () {
  66869. /**
  66870. * Instantiates a depth renderer
  66871. * @param scene The scene the renderer belongs to
  66872. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  66873. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  66874. */
  66875. function DepthRenderer(scene, type, camera) {
  66876. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66877. if (camera === void 0) { camera = null; }
  66878. var _this = this;
  66879. this._scene = scene;
  66880. this._camera = camera;
  66881. var engine = scene.getEngine();
  66882. // Render target
  66883. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  66884. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66885. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66886. this._depthMap.refreshRate = 1;
  66887. this._depthMap.renderParticles = false;
  66888. this._depthMap.renderList = null;
  66889. // Camera to get depth map from to support multiple concurrent cameras
  66890. this._depthMap.activeCamera = this._camera;
  66891. this._depthMap.ignoreCameraViewport = true;
  66892. this._depthMap.useCameraPostProcesses = false;
  66893. // set default depth value to 1.0 (far away)
  66894. this._depthMap.onClearObservable.add(function (engine) {
  66895. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  66896. });
  66897. // Custom render function
  66898. var renderSubMesh = function (subMesh) {
  66899. var mesh = subMesh.getRenderingMesh();
  66900. var scene = _this._scene;
  66901. var engine = scene.getEngine();
  66902. var material = subMesh.getMaterial();
  66903. if (!material) {
  66904. return;
  66905. }
  66906. // Culling and reverse (right handed system)
  66907. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66908. // Managing instances
  66909. var batch = mesh._getInstancesRenderList(subMesh._id);
  66910. if (batch.mustReturn) {
  66911. return;
  66912. }
  66913. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66914. var camera = _this._camera || scene.activeCamera;
  66915. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  66916. engine.enableEffect(_this._effect);
  66917. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66918. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66919. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  66920. // Alpha test
  66921. if (material && material.needAlphaTesting()) {
  66922. var alphaTexture = material.getAlphaTestTexture();
  66923. if (alphaTexture) {
  66924. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66925. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66926. }
  66927. }
  66928. // Bones
  66929. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66930. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66931. }
  66932. // Draw
  66933. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66934. }
  66935. };
  66936. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66937. var index;
  66938. if (depthOnlySubMeshes.length) {
  66939. engine.setColorWrite(false);
  66940. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66941. renderSubMesh(depthOnlySubMeshes.data[index]);
  66942. }
  66943. engine.setColorWrite(true);
  66944. }
  66945. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66946. renderSubMesh(opaqueSubMeshes.data[index]);
  66947. }
  66948. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66949. renderSubMesh(alphaTestSubMeshes.data[index]);
  66950. }
  66951. };
  66952. }
  66953. /**
  66954. * Creates the depth rendering effect and checks if the effect is ready.
  66955. * @param subMesh The submesh to be used to render the depth map of
  66956. * @param useInstances If multiple world instances should be used
  66957. * @returns if the depth renderer is ready to render the depth map
  66958. */
  66959. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  66960. var material = subMesh.getMaterial();
  66961. if (material.disableDepthWrite) {
  66962. return false;
  66963. }
  66964. var defines = [];
  66965. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66966. var mesh = subMesh.getMesh();
  66967. // Alpha test
  66968. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  66969. defines.push("#define ALPHATEST");
  66970. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66971. attribs.push(BABYLON.VertexBuffer.UVKind);
  66972. defines.push("#define UV1");
  66973. }
  66974. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66975. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66976. defines.push("#define UV2");
  66977. }
  66978. }
  66979. // Bones
  66980. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66981. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66982. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66983. if (mesh.numBoneInfluencers > 4) {
  66984. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66985. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66986. }
  66987. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66988. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66989. }
  66990. else {
  66991. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66992. }
  66993. // Instances
  66994. if (useInstances) {
  66995. defines.push("#define INSTANCES");
  66996. attribs.push("world0");
  66997. attribs.push("world1");
  66998. attribs.push("world2");
  66999. attribs.push("world3");
  67000. }
  67001. // Get correct effect
  67002. var join = defines.join("\n");
  67003. if (this._cachedDefines !== join) {
  67004. this._cachedDefines = join;
  67005. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  67006. }
  67007. return this._effect.isReady();
  67008. };
  67009. /**
  67010. * Gets the texture which the depth map will be written to.
  67011. * @returns The depth map texture
  67012. */
  67013. DepthRenderer.prototype.getDepthMap = function () {
  67014. return this._depthMap;
  67015. };
  67016. /**
  67017. * Disposes of the depth renderer.
  67018. */
  67019. DepthRenderer.prototype.dispose = function () {
  67020. this._depthMap.dispose();
  67021. };
  67022. return DepthRenderer;
  67023. }());
  67024. BABYLON.DepthRenderer = DepthRenderer;
  67025. })(BABYLON || (BABYLON = {}));
  67026. //# sourceMappingURL=babylon.depthRenderer.js.map
  67027. var BABYLON;
  67028. (function (BABYLON) {
  67029. var SSAORenderingPipeline = /** @class */ (function (_super) {
  67030. __extends(SSAORenderingPipeline, _super);
  67031. /**
  67032. * @constructor
  67033. * @param {string} name - The rendering pipeline name
  67034. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67035. * @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 }
  67036. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67037. */
  67038. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  67039. var _this = _super.call(this, scene.getEngine(), name) || this;
  67040. // Members
  67041. /**
  67042. * The PassPostProcess id in the pipeline that contains the original scene color
  67043. * @type {string}
  67044. */
  67045. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67046. /**
  67047. * The SSAO PostProcess id in the pipeline
  67048. * @type {string}
  67049. */
  67050. _this.SSAORenderEffect = "SSAORenderEffect";
  67051. /**
  67052. * The horizontal blur PostProcess id in the pipeline
  67053. * @type {string}
  67054. */
  67055. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67056. /**
  67057. * The vertical blur PostProcess id in the pipeline
  67058. * @type {string}
  67059. */
  67060. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67061. /**
  67062. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67063. * @type {string}
  67064. */
  67065. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67066. /**
  67067. * The output strength of the SSAO post-process. Default value is 1.0.
  67068. * @type {number}
  67069. */
  67070. _this.totalStrength = 1.0;
  67071. /**
  67072. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  67073. * @type {number}
  67074. */
  67075. _this.radius = 0.0001;
  67076. /**
  67077. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  67078. * Must not be equal to fallOff and superior to fallOff.
  67079. * Default value is 0.975
  67080. * @type {number}
  67081. */
  67082. _this.area = 0.0075;
  67083. /**
  67084. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  67085. * Must not be equal to area and inferior to area.
  67086. * Default value is 0.0
  67087. * @type {number}
  67088. */
  67089. _this.fallOff = 0.000001;
  67090. /**
  67091. * The base color of the SSAO post-process
  67092. * The final result is "base + ssao" between [0, 1]
  67093. * @type {number}
  67094. */
  67095. _this.base = 0.5;
  67096. _this._firstUpdate = true;
  67097. _this._scene = scene;
  67098. // Set up assets
  67099. _this._createRandomTexture();
  67100. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67101. var ssaoRatio = ratio.ssaoRatio || ratio;
  67102. var combineRatio = ratio.combineRatio || ratio;
  67103. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67104. _this._createSSAOPostProcess(ssaoRatio);
  67105. _this._createBlurPostProcess(ssaoRatio);
  67106. _this._createSSAOCombinePostProcess(combineRatio);
  67107. // Set up pipeline
  67108. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67109. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67110. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67111. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67112. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67113. // Finish
  67114. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67115. if (cameras)
  67116. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67117. return _this;
  67118. }
  67119. // Public Methods
  67120. /**
  67121. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67122. */
  67123. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67124. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67125. for (var i = 0; i < this._scene.cameras.length; i++) {
  67126. var camera = this._scene.cameras[i];
  67127. this._originalColorPostProcess.dispose(camera);
  67128. this._ssaoPostProcess.dispose(camera);
  67129. this._blurHPostProcess.dispose(camera);
  67130. this._blurVPostProcess.dispose(camera);
  67131. this._ssaoCombinePostProcess.dispose(camera);
  67132. }
  67133. this._randomTexture.dispose();
  67134. if (disableDepthRender)
  67135. this._scene.disableDepthRenderer();
  67136. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67137. _super.prototype.dispose.call(this);
  67138. };
  67139. // Private Methods
  67140. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  67141. var _this = this;
  67142. var size = 16;
  67143. 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);
  67144. 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);
  67145. this._blurHPostProcess.onActivateObservable.add(function () {
  67146. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  67147. _this._blurHPostProcess.kernel = size * dw;
  67148. });
  67149. this._blurVPostProcess.onActivateObservable.add(function () {
  67150. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  67151. _this._blurVPostProcess.kernel = size * dw;
  67152. });
  67153. };
  67154. SSAORenderingPipeline.prototype._rebuild = function () {
  67155. this._firstUpdate = true;
  67156. _super.prototype._rebuild.call(this);
  67157. };
  67158. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67159. var _this = this;
  67160. var numSamples = 16;
  67161. var sampleSphere = [
  67162. 0.5381, 0.1856, -0.4319,
  67163. 0.1379, 0.2486, 0.4430,
  67164. 0.3371, 0.5679, -0.0057,
  67165. -0.6999, -0.0451, -0.0019,
  67166. 0.0689, -0.1598, -0.8547,
  67167. 0.0560, 0.0069, -0.1843,
  67168. -0.0146, 0.1402, 0.0762,
  67169. 0.0100, -0.1924, -0.0344,
  67170. -0.3577, -0.5301, -0.4358,
  67171. -0.3169, 0.1063, 0.0158,
  67172. 0.0103, -0.5869, 0.0046,
  67173. -0.0897, -0.4940, 0.3287,
  67174. 0.7119, -0.0154, -0.0918,
  67175. -0.0533, 0.0596, -0.5411,
  67176. 0.0352, -0.0631, 0.5460,
  67177. -0.4776, 0.2847, -0.0271
  67178. ];
  67179. var samplesFactor = 1.0 / numSamples;
  67180. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  67181. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67182. "area", "fallOff", "base", "range", "viewport"
  67183. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67184. this._ssaoPostProcess.onApply = function (effect) {
  67185. if (_this._firstUpdate) {
  67186. effect.setArray3("sampleSphere", sampleSphere);
  67187. effect.setFloat("samplesFactor", samplesFactor);
  67188. effect.setFloat("randTextureTiles", 4.0);
  67189. }
  67190. effect.setFloat("totalStrength", _this.totalStrength);
  67191. effect.setFloat("radius", _this.radius);
  67192. effect.setFloat("area", _this.area);
  67193. effect.setFloat("fallOff", _this.fallOff);
  67194. effect.setFloat("base", _this.base);
  67195. effect.setTexture("textureSampler", _this._depthTexture);
  67196. effect.setTexture("randomSampler", _this._randomTexture);
  67197. };
  67198. };
  67199. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67200. var _this = this;
  67201. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67202. this._ssaoCombinePostProcess.onApply = function (effect) {
  67203. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67204. };
  67205. };
  67206. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  67207. var size = 512;
  67208. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67209. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67210. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67211. var context = this._randomTexture.getContext();
  67212. var rand = function (min, max) {
  67213. return Math.random() * (max - min) + min;
  67214. };
  67215. var randVector = BABYLON.Vector3.Zero();
  67216. for (var x = 0; x < size; x++) {
  67217. for (var y = 0; y < size; y++) {
  67218. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  67219. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  67220. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  67221. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67222. context.fillRect(x, y, 1, 1);
  67223. }
  67224. }
  67225. this._randomTexture.update(false);
  67226. };
  67227. __decorate([
  67228. BABYLON.serialize()
  67229. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  67230. __decorate([
  67231. BABYLON.serialize()
  67232. ], SSAORenderingPipeline.prototype, "radius", void 0);
  67233. __decorate([
  67234. BABYLON.serialize()
  67235. ], SSAORenderingPipeline.prototype, "area", void 0);
  67236. __decorate([
  67237. BABYLON.serialize()
  67238. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  67239. __decorate([
  67240. BABYLON.serialize()
  67241. ], SSAORenderingPipeline.prototype, "base", void 0);
  67242. return SSAORenderingPipeline;
  67243. }(BABYLON.PostProcessRenderPipeline));
  67244. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  67245. })(BABYLON || (BABYLON = {}));
  67246. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  67247. var BABYLON;
  67248. (function (BABYLON) {
  67249. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  67250. __extends(SSAO2RenderingPipeline, _super);
  67251. /**
  67252. * @constructor
  67253. * @param {string} name - The rendering pipeline name
  67254. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67255. * @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 }
  67256. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67257. */
  67258. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  67259. var _this = _super.call(this, scene.getEngine(), name) || this;
  67260. // Members
  67261. /**
  67262. * The PassPostProcess id in the pipeline that contains the original scene color
  67263. * @type {string}
  67264. */
  67265. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67266. /**
  67267. * The SSAO PostProcess id in the pipeline
  67268. * @type {string}
  67269. */
  67270. _this.SSAORenderEffect = "SSAORenderEffect";
  67271. /**
  67272. * The horizontal blur PostProcess id in the pipeline
  67273. * @type {string}
  67274. */
  67275. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67276. /**
  67277. * The vertical blur PostProcess id in the pipeline
  67278. * @type {string}
  67279. */
  67280. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67281. /**
  67282. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67283. * @type {string}
  67284. */
  67285. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67286. /**
  67287. * The output strength of the SSAO post-process. Default value is 1.0.
  67288. * @type {number}
  67289. */
  67290. _this.totalStrength = 1.0;
  67291. /**
  67292. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  67293. * @type {number}
  67294. */
  67295. _this.maxZ = 100.0;
  67296. /**
  67297. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  67298. * @type {number}
  67299. */
  67300. _this.minZAspect = 0.2;
  67301. /**
  67302. * Number of samples used for the SSAO calculations. Default value is 8
  67303. * @type {number}
  67304. */
  67305. _this._samples = 8;
  67306. /**
  67307. * Are we using bilateral blur ?
  67308. * @type {boolean}
  67309. */
  67310. _this._expensiveBlur = true;
  67311. /**
  67312. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  67313. * @type {number}
  67314. */
  67315. _this.radius = 2.0;
  67316. /**
  67317. * The base color of the SSAO post-process
  67318. * The final result is "base + ssao" between [0, 1]
  67319. * @type {number}
  67320. */
  67321. _this.base = 0.1;
  67322. _this._firstUpdate = true;
  67323. _this._scene = scene;
  67324. if (!_this.isSupported) {
  67325. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  67326. return _this;
  67327. }
  67328. var ssaoRatio = ratio.ssaoRatio || ratio;
  67329. var blurRatio = ratio.blurRatio || ratio;
  67330. // Set up assets
  67331. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  67332. _this._createRandomTexture();
  67333. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  67334. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  67335. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67336. _this._createSSAOPostProcess(1.0);
  67337. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  67338. _this._createSSAOCombinePostProcess(blurRatio);
  67339. // Set up pipeline
  67340. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67341. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67342. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67343. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67344. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67345. // Finish
  67346. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67347. if (cameras)
  67348. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67349. return _this;
  67350. }
  67351. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  67352. get: function () {
  67353. return this._samples;
  67354. },
  67355. set: function (n) {
  67356. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  67357. this._samples = n;
  67358. this._sampleSphere = this._generateHemisphere();
  67359. this._firstUpdate = true;
  67360. },
  67361. enumerable: true,
  67362. configurable: true
  67363. });
  67364. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  67365. get: function () {
  67366. return this._expensiveBlur;
  67367. },
  67368. set: function (b) {
  67369. 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"]);
  67370. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  67371. this._expensiveBlur = b;
  67372. this._firstUpdate = true;
  67373. },
  67374. enumerable: true,
  67375. configurable: true
  67376. });
  67377. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  67378. /**
  67379. * Support test.
  67380. * @type {boolean}
  67381. */
  67382. get: function () {
  67383. var engine = BABYLON.Engine.LastCreatedEngine;
  67384. if (!engine) {
  67385. return false;
  67386. }
  67387. return engine.getCaps().drawBuffersExtension;
  67388. },
  67389. enumerable: true,
  67390. configurable: true
  67391. });
  67392. // Public Methods
  67393. /**
  67394. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67395. */
  67396. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  67397. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  67398. for (var i = 0; i < this._scene.cameras.length; i++) {
  67399. var camera = this._scene.cameras[i];
  67400. this._originalColorPostProcess.dispose(camera);
  67401. this._ssaoPostProcess.dispose(camera);
  67402. this._blurHPostProcess.dispose(camera);
  67403. this._blurVPostProcess.dispose(camera);
  67404. this._ssaoCombinePostProcess.dispose(camera);
  67405. }
  67406. this._randomTexture.dispose();
  67407. if (disableGeometryBufferRenderer)
  67408. this._scene.disableGeometryBufferRenderer();
  67409. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67410. _super.prototype.dispose.call(this);
  67411. };
  67412. // Private Methods
  67413. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  67414. var _this = this;
  67415. this._samplerOffsets = [];
  67416. var expensive = this.expensiveBlur;
  67417. for (var i = -8; i < 8; i++) {
  67418. this._samplerOffsets.push(i * 2 + 0.5);
  67419. }
  67420. 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");
  67421. this._blurHPostProcess.onApply = function (effect) {
  67422. if (!_this._scene.activeCamera) {
  67423. return;
  67424. }
  67425. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  67426. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67427. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67428. effect.setFloat("radius", _this.radius);
  67429. effect.setTexture("depthSampler", _this._depthTexture);
  67430. if (_this._firstUpdate) {
  67431. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67432. }
  67433. };
  67434. 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");
  67435. this._blurVPostProcess.onApply = function (effect) {
  67436. if (!_this._scene.activeCamera) {
  67437. return;
  67438. }
  67439. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  67440. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67441. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67442. effect.setFloat("radius", _this.radius);
  67443. effect.setTexture("depthSampler", _this._depthTexture);
  67444. if (_this._firstUpdate) {
  67445. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67446. _this._firstUpdate = false;
  67447. }
  67448. };
  67449. };
  67450. SSAO2RenderingPipeline.prototype._rebuild = function () {
  67451. this._firstUpdate = true;
  67452. _super.prototype._rebuild.call(this);
  67453. };
  67454. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  67455. var numSamples = this.samples;
  67456. var result = [];
  67457. var vector, scale;
  67458. var rand = function (min, max) {
  67459. return Math.random() * (max - min) + min;
  67460. };
  67461. var i = 0;
  67462. while (i < numSamples) {
  67463. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  67464. vector.normalize();
  67465. scale = i / numSamples;
  67466. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  67467. vector.scaleInPlace(scale);
  67468. result.push(vector.x, vector.y, vector.z);
  67469. i++;
  67470. }
  67471. return result;
  67472. };
  67473. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67474. var _this = this;
  67475. var numSamples = this.samples;
  67476. this._sampleSphere = this._generateHemisphere();
  67477. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  67478. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67479. "base", "range", "projection", "near", "far", "texelSize",
  67480. "xViewport", "yViewport", "maxZ", "minZAspect"
  67481. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67482. this._ssaoPostProcess.onApply = function (effect) {
  67483. if (_this._firstUpdate) {
  67484. effect.setArray3("sampleSphere", _this._sampleSphere);
  67485. effect.setFloat("randTextureTiles", 4.0);
  67486. }
  67487. if (!_this._scene.activeCamera) {
  67488. return;
  67489. }
  67490. effect.setFloat("samplesFactor", 1 / _this.samples);
  67491. effect.setFloat("totalStrength", _this.totalStrength);
  67492. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  67493. effect.setFloat("radius", _this.radius);
  67494. effect.setFloat("maxZ", _this.maxZ);
  67495. effect.setFloat("minZAspect", _this.minZAspect);
  67496. effect.setFloat("base", _this.base);
  67497. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67498. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67499. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  67500. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  67501. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  67502. effect.setTexture("textureSampler", _this._depthTexture);
  67503. effect.setTexture("normalSampler", _this._normalTexture);
  67504. effect.setTexture("randomSampler", _this._randomTexture);
  67505. };
  67506. };
  67507. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67508. var _this = this;
  67509. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67510. this._ssaoCombinePostProcess.onApply = function (effect) {
  67511. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67512. };
  67513. };
  67514. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  67515. var size = 512;
  67516. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67517. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67518. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67519. var context = this._randomTexture.getContext();
  67520. var rand = function (min, max) {
  67521. return Math.random() * (max - min) + min;
  67522. };
  67523. var randVector = BABYLON.Vector3.Zero();
  67524. for (var x = 0; x < size; x++) {
  67525. for (var y = 0; y < size; y++) {
  67526. randVector.x = rand(0.0, 1.0);
  67527. randVector.y = rand(0.0, 1.0);
  67528. randVector.z = 0.0;
  67529. randVector.normalize();
  67530. randVector.scaleInPlace(255);
  67531. randVector.x = Math.floor(randVector.x);
  67532. randVector.y = Math.floor(randVector.y);
  67533. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67534. context.fillRect(x, y, 1, 1);
  67535. }
  67536. }
  67537. this._randomTexture.update(false);
  67538. };
  67539. __decorate([
  67540. BABYLON.serialize()
  67541. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  67542. __decorate([
  67543. BABYLON.serialize()
  67544. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  67545. __decorate([
  67546. BABYLON.serialize()
  67547. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  67548. __decorate([
  67549. BABYLON.serialize("samples")
  67550. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  67551. __decorate([
  67552. BABYLON.serialize("expensiveBlur")
  67553. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  67554. __decorate([
  67555. BABYLON.serialize()
  67556. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  67557. __decorate([
  67558. BABYLON.serialize()
  67559. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  67560. return SSAO2RenderingPipeline;
  67561. }(BABYLON.PostProcessRenderPipeline));
  67562. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  67563. })(BABYLON || (BABYLON = {}));
  67564. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  67565. // BABYLON.JS Chromatic Aberration GLSL Shader
  67566. // Author: Olivier Guyot
  67567. // Separates very slightly R, G and B colors on the edges of the screen
  67568. // Inspired by Francois Tarlier & Martins Upitis
  67569. var BABYLON;
  67570. (function (BABYLON) {
  67571. var LensRenderingPipeline = /** @class */ (function (_super) {
  67572. __extends(LensRenderingPipeline, _super);
  67573. /**
  67574. * @constructor
  67575. *
  67576. * Effect parameters are as follow:
  67577. * {
  67578. * chromatic_aberration: number; // from 0 to x (1 for realism)
  67579. * edge_blur: number; // from 0 to x (1 for realism)
  67580. * distortion: number; // from 0 to x (1 for realism)
  67581. * grain_amount: number; // from 0 to 1
  67582. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  67583. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  67584. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  67585. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  67586. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  67587. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  67588. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  67589. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  67590. * }
  67591. * Note: if an effect parameter is unset, effect is disabled
  67592. *
  67593. * @param {string} name - The rendering pipeline name
  67594. * @param {object} parameters - An object containing all parameters (see above)
  67595. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67596. * @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)
  67597. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67598. */
  67599. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  67600. if (ratio === void 0) { ratio = 1.0; }
  67601. var _this = _super.call(this, scene.getEngine(), name) || this;
  67602. // Lens effects can be of the following:
  67603. // - chromatic aberration (slight shift of RGB colors)
  67604. // - blur on the edge of the lens
  67605. // - lens distortion
  67606. // - depth-of-field blur & highlights enhancing
  67607. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  67608. // - grain effect (noise or custom texture)
  67609. // Two additional texture samplers are needed:
  67610. // - depth map (for depth-of-field)
  67611. // - grain texture
  67612. /**
  67613. * The chromatic aberration PostProcess id in the pipeline
  67614. * @type {string}
  67615. */
  67616. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  67617. /**
  67618. * The highlights enhancing PostProcess id in the pipeline
  67619. * @type {string}
  67620. */
  67621. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  67622. /**
  67623. * The depth-of-field PostProcess id in the pipeline
  67624. * @type {string}
  67625. */
  67626. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  67627. _this._scene = scene;
  67628. // Fetch texture samplers
  67629. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67630. if (parameters.grain_texture) {
  67631. _this._grainTexture = parameters.grain_texture;
  67632. }
  67633. else {
  67634. _this._createGrainTexture();
  67635. }
  67636. // save parameters
  67637. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  67638. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  67639. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  67640. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  67641. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  67642. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  67643. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  67644. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  67645. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  67646. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  67647. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  67648. // Create effects
  67649. _this._createChromaticAberrationPostProcess(ratio);
  67650. _this._createHighlightsPostProcess(ratio);
  67651. _this._createDepthOfFieldPostProcess(ratio / 4);
  67652. // Set up pipeline
  67653. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  67654. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  67655. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  67656. if (_this._highlightsGain === -1) {
  67657. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  67658. }
  67659. // Finish
  67660. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67661. if (cameras) {
  67662. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67663. }
  67664. return _this;
  67665. }
  67666. // public methods (self explanatory)
  67667. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  67668. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  67669. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  67670. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  67671. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  67672. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  67673. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  67674. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  67675. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  67676. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  67677. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  67678. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  67679. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  67680. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67681. };
  67682. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67683. this._highlightsPostProcess.updateEffect();
  67684. };
  67685. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67686. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67687. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67688. this._highlightsGain = amount;
  67689. };
  67690. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67691. if (this._highlightsGain === -1) {
  67692. this._highlightsGain = 1.0;
  67693. }
  67694. this._highlightsThreshold = amount;
  67695. };
  67696. LensRenderingPipeline.prototype.disableHighlights = function () {
  67697. this._highlightsGain = -1;
  67698. };
  67699. /**
  67700. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67701. */
  67702. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67703. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67704. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67705. this._chromaticAberrationPostProcess = null;
  67706. this._highlightsPostProcess = null;
  67707. this._depthOfFieldPostProcess = null;
  67708. this._grainTexture.dispose();
  67709. if (disableDepthRender)
  67710. this._scene.disableDepthRenderer();
  67711. };
  67712. // colors shifting and distortion
  67713. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67714. var _this = this;
  67715. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  67716. [], // samplers
  67717. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67718. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67719. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67720. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67721. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67722. effect.setFloat('radialIntensity', 1);
  67723. effect.setFloat2('direction', 17, 17);
  67724. effect.setFloat2('centerPosition', 0.5, 0.5);
  67725. };
  67726. };
  67727. // highlights enhancing
  67728. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67729. var _this = this;
  67730. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67731. [], // samplers
  67732. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67733. this._highlightsPostProcess.onApply = function (effect) {
  67734. effect.setFloat('gain', _this._highlightsGain);
  67735. effect.setFloat('threshold', _this._highlightsThreshold);
  67736. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67737. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67738. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67739. };
  67740. };
  67741. // colors shifting and distortion
  67742. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67743. var _this = this;
  67744. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67745. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67746. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67747. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67748. this._depthOfFieldPostProcess.onApply = function (effect) {
  67749. effect.setTexture("depthSampler", _this._depthTexture);
  67750. effect.setTexture("grainSampler", _this._grainTexture);
  67751. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67752. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67753. effect.setFloat('grain_amount', _this._grainAmount);
  67754. effect.setBool('blur_noise', _this._blurNoise);
  67755. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67756. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67757. effect.setFloat('distortion', _this._distortion);
  67758. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67759. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67760. effect.setFloat('aperture', _this._dofAperture);
  67761. effect.setFloat('darken', _this._dofDarken);
  67762. effect.setFloat('edge_blur', _this._edgeBlur);
  67763. effect.setBool('highlights', (_this._highlightsGain !== -1));
  67764. if (_this._scene.activeCamera) {
  67765. effect.setFloat('near', _this._scene.activeCamera.minZ);
  67766. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  67767. }
  67768. };
  67769. };
  67770. // creates a black and white random noise texture, 512x512
  67771. LensRenderingPipeline.prototype._createGrainTexture = function () {
  67772. var size = 512;
  67773. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67774. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67775. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67776. var context = this._grainTexture.getContext();
  67777. var rand = function (min, max) {
  67778. return Math.random() * (max - min) + min;
  67779. };
  67780. var value;
  67781. for (var x = 0; x < size; x++) {
  67782. for (var y = 0; y < size; y++) {
  67783. value = Math.floor(rand(0.42, 0.58) * 255);
  67784. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  67785. context.fillRect(x, y, 1, 1);
  67786. }
  67787. }
  67788. this._grainTexture.update(false);
  67789. };
  67790. return LensRenderingPipeline;
  67791. }(BABYLON.PostProcessRenderPipeline));
  67792. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  67793. })(BABYLON || (BABYLON = {}));
  67794. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  67795. var BABYLON;
  67796. (function (BABYLON) {
  67797. var StandardRenderingPipeline = /** @class */ (function (_super) {
  67798. __extends(StandardRenderingPipeline, _super);
  67799. /**
  67800. * @constructor
  67801. * @param {string} name - The rendering pipeline name
  67802. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67803. * @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)
  67804. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  67805. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67806. */
  67807. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  67808. if (originalPostProcess === void 0) { originalPostProcess = null; }
  67809. var _this = _super.call(this, scene.getEngine(), name) || this;
  67810. _this.downSampleX4PostProcess = null;
  67811. _this.brightPassPostProcess = null;
  67812. _this.blurHPostProcesses = [];
  67813. _this.blurVPostProcesses = [];
  67814. _this.textureAdderPostProcess = null;
  67815. _this.volumetricLightPostProcess = null;
  67816. _this.volumetricLightSmoothXPostProcess = null;
  67817. _this.volumetricLightSmoothYPostProcess = null;
  67818. _this.volumetricLightMergePostProces = null;
  67819. _this.volumetricLightFinalPostProcess = null;
  67820. _this.luminancePostProcess = null;
  67821. _this.luminanceDownSamplePostProcesses = [];
  67822. _this.hdrPostProcess = null;
  67823. _this.textureAdderFinalPostProcess = null;
  67824. _this.lensFlareFinalPostProcess = null;
  67825. _this.hdrFinalPostProcess = null;
  67826. _this.lensFlarePostProcess = null;
  67827. _this.lensFlareComposePostProcess = null;
  67828. _this.motionBlurPostProcess = null;
  67829. _this.depthOfFieldPostProcess = null;
  67830. // Values
  67831. _this.brightThreshold = 1.0;
  67832. _this.blurWidth = 512.0;
  67833. _this.horizontalBlur = false;
  67834. _this.exposure = 1.0;
  67835. _this.lensTexture = null;
  67836. _this.volumetricLightCoefficient = 0.2;
  67837. _this.volumetricLightPower = 4.0;
  67838. _this.volumetricLightBlurScale = 64.0;
  67839. _this.sourceLight = null;
  67840. _this.hdrMinimumLuminance = 1.0;
  67841. _this.hdrDecreaseRate = 0.5;
  67842. _this.hdrIncreaseRate = 0.5;
  67843. _this.lensColorTexture = null;
  67844. _this.lensFlareStrength = 20.0;
  67845. _this.lensFlareGhostDispersal = 1.4;
  67846. _this.lensFlareHaloWidth = 0.7;
  67847. _this.lensFlareDistortionStrength = 16.0;
  67848. _this.lensStarTexture = null;
  67849. _this.lensFlareDirtTexture = null;
  67850. _this.depthOfFieldDistance = 10.0;
  67851. _this.depthOfFieldBlurWidth = 64.0;
  67852. _this.motionStrength = 1.0;
  67853. // IAnimatable
  67854. _this.animations = [];
  67855. _this._currentDepthOfFieldSource = null;
  67856. _this._hdrCurrentLuminance = 1.0;
  67857. // Getters and setters
  67858. _this._bloomEnabled = true;
  67859. _this._depthOfFieldEnabled = false;
  67860. _this._vlsEnabled = false;
  67861. _this._lensFlareEnabled = false;
  67862. _this._hdrEnabled = false;
  67863. _this._motionBlurEnabled = false;
  67864. _this._motionBlurSamples = 64.0;
  67865. _this._volumetricLightStepsCount = 50.0;
  67866. _this._cameras = cameras || [];
  67867. // Initialize
  67868. _this._scene = scene;
  67869. _this._basePostProcess = originalPostProcess;
  67870. _this._ratio = ratio;
  67871. // Misc
  67872. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67873. // Finish
  67874. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67875. _this._buildPipeline();
  67876. return _this;
  67877. }
  67878. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  67879. get: function () {
  67880. return this._bloomEnabled;
  67881. },
  67882. set: function (enabled) {
  67883. if (this._bloomEnabled === enabled) {
  67884. return;
  67885. }
  67886. this._bloomEnabled = enabled;
  67887. this._buildPipeline();
  67888. },
  67889. enumerable: true,
  67890. configurable: true
  67891. });
  67892. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  67893. get: function () {
  67894. return this._depthOfFieldEnabled;
  67895. },
  67896. set: function (enabled) {
  67897. if (this._depthOfFieldEnabled === enabled) {
  67898. return;
  67899. }
  67900. this._depthOfFieldEnabled = enabled;
  67901. this._buildPipeline();
  67902. },
  67903. enumerable: true,
  67904. configurable: true
  67905. });
  67906. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  67907. get: function () {
  67908. return this._lensFlareEnabled;
  67909. },
  67910. set: function (enabled) {
  67911. if (this._lensFlareEnabled === enabled) {
  67912. return;
  67913. }
  67914. this._lensFlareEnabled = enabled;
  67915. this._buildPipeline();
  67916. },
  67917. enumerable: true,
  67918. configurable: true
  67919. });
  67920. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  67921. get: function () {
  67922. return this._hdrEnabled;
  67923. },
  67924. set: function (enabled) {
  67925. if (this._hdrEnabled === enabled) {
  67926. return;
  67927. }
  67928. this._hdrEnabled = enabled;
  67929. this._buildPipeline();
  67930. },
  67931. enumerable: true,
  67932. configurable: true
  67933. });
  67934. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  67935. get: function () {
  67936. return this._vlsEnabled;
  67937. },
  67938. set: function (enabled) {
  67939. if (this._vlsEnabled === enabled) {
  67940. return;
  67941. }
  67942. if (enabled) {
  67943. var geometry = this._scene.enableGeometryBufferRenderer();
  67944. if (!geometry) {
  67945. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  67946. return;
  67947. }
  67948. }
  67949. this._vlsEnabled = enabled;
  67950. this._buildPipeline();
  67951. },
  67952. enumerable: true,
  67953. configurable: true
  67954. });
  67955. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  67956. get: function () {
  67957. return this._motionBlurEnabled;
  67958. },
  67959. set: function (enabled) {
  67960. if (this._motionBlurEnabled === enabled) {
  67961. return;
  67962. }
  67963. this._motionBlurEnabled = enabled;
  67964. this._buildPipeline();
  67965. },
  67966. enumerable: true,
  67967. configurable: true
  67968. });
  67969. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  67970. get: function () {
  67971. return this._volumetricLightStepsCount;
  67972. },
  67973. set: function (count) {
  67974. if (this.volumetricLightPostProcess) {
  67975. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  67976. }
  67977. this._volumetricLightStepsCount = count;
  67978. },
  67979. enumerable: true,
  67980. configurable: true
  67981. });
  67982. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  67983. get: function () {
  67984. return this._motionBlurSamples;
  67985. },
  67986. set: function (samples) {
  67987. if (this.motionBlurPostProcess) {
  67988. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67989. }
  67990. this._motionBlurSamples = samples;
  67991. },
  67992. enumerable: true,
  67993. configurable: true
  67994. });
  67995. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67996. var _this = this;
  67997. var ratio = this._ratio;
  67998. var scene = this._scene;
  67999. this._disposePostProcesses();
  68000. this._reset();
  68001. // Create pass post-process
  68002. if (!this._basePostProcess) {
  68003. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  68004. this.originalPostProcess.onApply = function (effect) {
  68005. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  68006. };
  68007. }
  68008. else {
  68009. this.originalPostProcess = this._basePostProcess;
  68010. }
  68011. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  68012. this._currentDepthOfFieldSource = this.originalPostProcess;
  68013. if (this._vlsEnabled) {
  68014. // Create volumetric light
  68015. this._createVolumetricLightPostProcess(scene, ratio);
  68016. // Create volumetric light final post-process
  68017. 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);
  68018. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  68019. }
  68020. if (this._bloomEnabled) {
  68021. // Create down sample X4 post-process
  68022. this._createDownSampleX4PostProcess(scene, ratio / 2);
  68023. // Create bright pass post-process
  68024. this._createBrightPassPostProcess(scene, ratio / 2);
  68025. // Create gaussian blur post-processes (down sampling blurs)
  68026. this._createBlurPostProcesses(scene, ratio / 4, 1);
  68027. // Create texture adder post-process
  68028. this._createTextureAdderPostProcess(scene, ratio);
  68029. // Create depth-of-field source post-process
  68030. 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);
  68031. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  68032. }
  68033. if (this._lensFlareEnabled) {
  68034. // Create lens flare post-process
  68035. this._createLensFlarePostProcess(scene, ratio);
  68036. // Create depth-of-field source post-process post lens-flare and disable it now
  68037. 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);
  68038. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  68039. }
  68040. if (this._hdrEnabled) {
  68041. // Create luminance
  68042. this._createLuminancePostProcesses(scene, this._floatTextureType);
  68043. // Create HDR
  68044. this._createHdrPostProcess(scene, ratio);
  68045. // Create depth-of-field source post-process post hdr and disable it now
  68046. 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);
  68047. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  68048. }
  68049. if (this._depthOfFieldEnabled) {
  68050. // Create gaussian blur used by depth-of-field
  68051. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  68052. // Create depth-of-field post-process
  68053. this._createDepthOfFieldPostProcess(scene, ratio);
  68054. }
  68055. if (this._motionBlurEnabled) {
  68056. // Create motion blur post-process
  68057. this._createMotionBlurPostProcess(scene, ratio);
  68058. }
  68059. if (this._cameras !== null) {
  68060. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68061. }
  68062. };
  68063. // Down Sample X4 Post-Processs
  68064. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  68065. var _this = this;
  68066. var downSampleX4Offsets = new Array(32);
  68067. 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);
  68068. this.downSampleX4PostProcess.onApply = function (effect) {
  68069. var id = 0;
  68070. var width = _this.downSampleX4PostProcess.width;
  68071. var height = _this.downSampleX4PostProcess.height;
  68072. for (var i = -2; i < 2; i++) {
  68073. for (var j = -2; j < 2; j++) {
  68074. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  68075. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  68076. id += 2;
  68077. }
  68078. }
  68079. effect.setArray2("dsOffsets", downSampleX4Offsets);
  68080. };
  68081. // Add to pipeline
  68082. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  68083. };
  68084. // Brightpass Post-Process
  68085. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  68086. var _this = this;
  68087. var brightOffsets = new Array(8);
  68088. 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);
  68089. this.brightPassPostProcess.onApply = function (effect) {
  68090. var sU = (1.0 / _this.brightPassPostProcess.width);
  68091. var sV = (1.0 / _this.brightPassPostProcess.height);
  68092. brightOffsets[0] = -0.5 * sU;
  68093. brightOffsets[1] = 0.5 * sV;
  68094. brightOffsets[2] = 0.5 * sU;
  68095. brightOffsets[3] = 0.5 * sV;
  68096. brightOffsets[4] = -0.5 * sU;
  68097. brightOffsets[5] = -0.5 * sV;
  68098. brightOffsets[6] = 0.5 * sU;
  68099. brightOffsets[7] = -0.5 * sV;
  68100. effect.setArray2("dsOffsets", brightOffsets);
  68101. effect.setFloat("brightThreshold", _this.brightThreshold);
  68102. };
  68103. // Add to pipeline
  68104. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  68105. };
  68106. // Create blur H&V post-processes
  68107. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  68108. var _this = this;
  68109. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  68110. var engine = scene.getEngine();
  68111. 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);
  68112. 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);
  68113. blurX.onActivateObservable.add(function () {
  68114. var dw = blurX.width / engine.getRenderWidth();
  68115. blurX.kernel = _this[blurWidthKey] * dw;
  68116. });
  68117. blurY.onActivateObservable.add(function () {
  68118. var dw = blurY.height / engine.getRenderHeight();
  68119. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  68120. });
  68121. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  68122. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  68123. this.blurHPostProcesses.push(blurX);
  68124. this.blurVPostProcesses.push(blurY);
  68125. };
  68126. // Create texture adder post-process
  68127. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  68128. var _this = this;
  68129. 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);
  68130. this.textureAdderPostProcess.onApply = function (effect) {
  68131. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  68132. effect.setTexture("lensSampler", _this.lensTexture);
  68133. effect.setFloat("exposure", _this.exposure);
  68134. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  68135. };
  68136. // Add to pipeline
  68137. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  68138. };
  68139. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  68140. var _this = this;
  68141. var geometryRenderer = scene.enableGeometryBufferRenderer();
  68142. geometryRenderer.enablePosition = true;
  68143. var geometry = geometryRenderer.getGBuffer();
  68144. // Base post-process
  68145. 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));
  68146. var depthValues = BABYLON.Vector2.Zero();
  68147. this.volumetricLightPostProcess.onApply = function (effect) {
  68148. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  68149. var generator = _this.sourceLight.getShadowGenerator();
  68150. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  68151. effect.setTexture("positionSampler", geometry.textures[2]);
  68152. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  68153. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  68154. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  68155. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  68156. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  68157. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  68158. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  68159. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  68160. effect.setVector2("depthValues", depthValues);
  68161. }
  68162. };
  68163. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  68164. // Smooth
  68165. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  68166. // Merge
  68167. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  68168. this.volumetricLightMergePostProces.onApply = function (effect) {
  68169. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  68170. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  68171. };
  68172. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  68173. };
  68174. // Create luminance
  68175. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  68176. var _this = this;
  68177. // Create luminance
  68178. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  68179. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  68180. var offsets = [];
  68181. this.luminancePostProcess.onApply = function (effect) {
  68182. var sU = (1.0 / _this.luminancePostProcess.width);
  68183. var sV = (1.0 / _this.luminancePostProcess.height);
  68184. offsets[0] = -0.5 * sU;
  68185. offsets[1] = 0.5 * sV;
  68186. offsets[2] = 0.5 * sU;
  68187. offsets[3] = 0.5 * sV;
  68188. offsets[4] = -0.5 * sU;
  68189. offsets[5] = -0.5 * sV;
  68190. offsets[6] = 0.5 * sU;
  68191. offsets[7] = -0.5 * sV;
  68192. effect.setArray2("lumOffsets", offsets);
  68193. };
  68194. // Add to pipeline
  68195. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  68196. // Create down sample luminance
  68197. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  68198. var size = Math.pow(3, i);
  68199. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  68200. if (i === 0) {
  68201. defines += "#define FINAL_DOWN_SAMPLER";
  68202. }
  68203. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  68204. this.luminanceDownSamplePostProcesses.push(postProcess);
  68205. }
  68206. // Create callbacks and add effects
  68207. var lastLuminance = this.luminancePostProcess;
  68208. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  68209. var downSampleOffsets = new Array(18);
  68210. pp.onApply = function (effect) {
  68211. if (!lastLuminance) {
  68212. return;
  68213. }
  68214. var id = 0;
  68215. for (var x = -1; x < 2; x++) {
  68216. for (var y = -1; y < 2; y++) {
  68217. downSampleOffsets[id] = x / lastLuminance.width;
  68218. downSampleOffsets[id + 1] = y / lastLuminance.height;
  68219. id += 2;
  68220. }
  68221. }
  68222. effect.setArray2("dsOffsets", downSampleOffsets);
  68223. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  68224. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68225. lastLuminance = _this.luminancePostProcess;
  68226. }
  68227. else {
  68228. lastLuminance = pp;
  68229. }
  68230. };
  68231. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68232. pp.onAfterRender = function (effect) {
  68233. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  68234. 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);
  68235. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  68236. };
  68237. }
  68238. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  68239. });
  68240. };
  68241. // Create HDR post-process
  68242. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  68243. var _this = this;
  68244. 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);
  68245. var outputLiminance = 1;
  68246. var time = 0;
  68247. var lastTime = 0;
  68248. this.hdrPostProcess.onApply = function (effect) {
  68249. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  68250. time += scene.getEngine().getDeltaTime();
  68251. if (outputLiminance < 0) {
  68252. outputLiminance = _this._hdrCurrentLuminance;
  68253. }
  68254. else {
  68255. var dt = (lastTime - time) / 1000.0;
  68256. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  68257. outputLiminance += _this.hdrDecreaseRate * dt;
  68258. }
  68259. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  68260. outputLiminance -= _this.hdrIncreaseRate * dt;
  68261. }
  68262. else {
  68263. outputLiminance = _this._hdrCurrentLuminance;
  68264. }
  68265. }
  68266. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  68267. effect.setFloat("averageLuminance", outputLiminance);
  68268. lastTime = time;
  68269. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  68270. };
  68271. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  68272. };
  68273. // Create lens flare post-process
  68274. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  68275. var _this = this;
  68276. 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);
  68277. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  68278. this._createBlurPostProcesses(scene, ratio / 4, 2);
  68279. 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);
  68280. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  68281. var resolution = new BABYLON.Vector2(0, 0);
  68282. // Lens flare
  68283. this.lensFlarePostProcess.onApply = function (effect) {
  68284. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  68285. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  68286. effect.setFloat("strength", _this.lensFlareStrength);
  68287. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  68288. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  68289. // Shift
  68290. resolution.x = _this.lensFlarePostProcess.width;
  68291. resolution.y = _this.lensFlarePostProcess.height;
  68292. effect.setVector2("resolution", resolution);
  68293. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  68294. };
  68295. // Compose
  68296. 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);
  68297. 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);
  68298. this.lensFlareComposePostProcess.onApply = function (effect) {
  68299. if (!_this._scene.activeCamera) {
  68300. return;
  68301. }
  68302. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68303. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  68304. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  68305. // Lens start rotation matrix
  68306. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  68307. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  68308. 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));
  68309. camRot *= 4.0;
  68310. 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);
  68311. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  68312. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  68313. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  68314. };
  68315. };
  68316. // Create depth-of-field post-process
  68317. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  68318. var _this = this;
  68319. 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);
  68320. this.depthOfFieldPostProcess.onApply = function (effect) {
  68321. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68322. effect.setTexture("depthSampler", _this._getDepthTexture());
  68323. effect.setFloat("distance", _this.depthOfFieldDistance);
  68324. };
  68325. // Add to pipeline
  68326. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  68327. };
  68328. // Create motion blur post-process
  68329. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  68330. var _this = this;
  68331. 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);
  68332. var motionScale = 0;
  68333. var prevViewProjection = BABYLON.Matrix.Identity();
  68334. var invViewProjection = BABYLON.Matrix.Identity();
  68335. var viewProjection = BABYLON.Matrix.Identity();
  68336. var screenSize = BABYLON.Vector2.Zero();
  68337. this.motionBlurPostProcess.onApply = function (effect) {
  68338. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  68339. viewProjection.invertToRef(invViewProjection);
  68340. effect.setMatrix("inverseViewProjection", invViewProjection);
  68341. effect.setMatrix("prevViewProjection", prevViewProjection);
  68342. prevViewProjection = viewProjection;
  68343. screenSize.x = _this.motionBlurPostProcess.width;
  68344. screenSize.y = _this.motionBlurPostProcess.height;
  68345. effect.setVector2("screenSize", screenSize);
  68346. motionScale = scene.getEngine().getFps() / 60.0;
  68347. effect.setFloat("motionScale", motionScale);
  68348. effect.setFloat("motionStrength", _this.motionStrength);
  68349. effect.setTexture("depthSampler", _this._getDepthTexture());
  68350. };
  68351. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  68352. };
  68353. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  68354. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  68355. var renderer = this._scene.enableGeometryBufferRenderer();
  68356. return renderer.getGBuffer().textures[0];
  68357. }
  68358. return this._scene.enableDepthRenderer().getDepthMap();
  68359. };
  68360. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  68361. for (var i = 0; i < this._cameras.length; i++) {
  68362. var camera = this._cameras[i];
  68363. if (this.originalPostProcess) {
  68364. this.originalPostProcess.dispose(camera);
  68365. }
  68366. if (this.downSampleX4PostProcess) {
  68367. this.downSampleX4PostProcess.dispose(camera);
  68368. }
  68369. if (this.brightPassPostProcess) {
  68370. this.brightPassPostProcess.dispose(camera);
  68371. }
  68372. if (this.textureAdderPostProcess) {
  68373. this.textureAdderPostProcess.dispose(camera);
  68374. }
  68375. if (this.textureAdderFinalPostProcess) {
  68376. this.textureAdderFinalPostProcess.dispose(camera);
  68377. }
  68378. if (this.volumetricLightPostProcess) {
  68379. this.volumetricLightPostProcess.dispose(camera);
  68380. }
  68381. if (this.volumetricLightSmoothXPostProcess) {
  68382. this.volumetricLightSmoothXPostProcess.dispose(camera);
  68383. }
  68384. if (this.volumetricLightSmoothYPostProcess) {
  68385. this.volumetricLightSmoothYPostProcess.dispose(camera);
  68386. }
  68387. if (this.volumetricLightMergePostProces) {
  68388. this.volumetricLightMergePostProces.dispose(camera);
  68389. }
  68390. if (this.volumetricLightFinalPostProcess) {
  68391. this.volumetricLightFinalPostProcess.dispose(camera);
  68392. }
  68393. if (this.lensFlarePostProcess) {
  68394. this.lensFlarePostProcess.dispose(camera);
  68395. }
  68396. if (this.lensFlareComposePostProcess) {
  68397. this.lensFlareComposePostProcess.dispose(camera);
  68398. }
  68399. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  68400. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  68401. }
  68402. if (this.luminancePostProcess) {
  68403. this.luminancePostProcess.dispose(camera);
  68404. }
  68405. if (this.hdrPostProcess) {
  68406. this.hdrPostProcess.dispose(camera);
  68407. }
  68408. if (this.hdrFinalPostProcess) {
  68409. this.hdrFinalPostProcess.dispose(camera);
  68410. }
  68411. if (this.depthOfFieldPostProcess) {
  68412. this.depthOfFieldPostProcess.dispose(camera);
  68413. }
  68414. if (this.motionBlurPostProcess) {
  68415. this.motionBlurPostProcess.dispose(camera);
  68416. }
  68417. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  68418. this.blurHPostProcesses[j].dispose(camera);
  68419. }
  68420. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  68421. this.blurVPostProcesses[j].dispose(camera);
  68422. }
  68423. }
  68424. this.originalPostProcess = null;
  68425. this.downSampleX4PostProcess = null;
  68426. this.brightPassPostProcess = null;
  68427. this.textureAdderPostProcess = null;
  68428. this.textureAdderFinalPostProcess = null;
  68429. this.volumetricLightPostProcess = null;
  68430. this.volumetricLightSmoothXPostProcess = null;
  68431. this.volumetricLightSmoothYPostProcess = null;
  68432. this.volumetricLightMergePostProces = null;
  68433. this.volumetricLightFinalPostProcess = null;
  68434. this.lensFlarePostProcess = null;
  68435. this.lensFlareComposePostProcess = null;
  68436. this.luminancePostProcess = null;
  68437. this.hdrPostProcess = null;
  68438. this.hdrFinalPostProcess = null;
  68439. this.depthOfFieldPostProcess = null;
  68440. this.motionBlurPostProcess = null;
  68441. this.luminanceDownSamplePostProcesses = [];
  68442. this.blurHPostProcesses = [];
  68443. this.blurVPostProcesses = [];
  68444. };
  68445. // Dispose
  68446. StandardRenderingPipeline.prototype.dispose = function () {
  68447. this._disposePostProcesses();
  68448. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68449. _super.prototype.dispose.call(this);
  68450. };
  68451. // Serialize rendering pipeline
  68452. StandardRenderingPipeline.prototype.serialize = function () {
  68453. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68454. serializationObject.customType = "StandardRenderingPipeline";
  68455. return serializationObject;
  68456. };
  68457. /**
  68458. * Static members
  68459. */
  68460. // Parse serialized pipeline
  68461. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68462. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  68463. };
  68464. // Luminance steps
  68465. StandardRenderingPipeline.LuminanceSteps = 6;
  68466. __decorate([
  68467. BABYLON.serialize()
  68468. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  68469. __decorate([
  68470. BABYLON.serialize()
  68471. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  68472. __decorate([
  68473. BABYLON.serialize()
  68474. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  68475. __decorate([
  68476. BABYLON.serialize()
  68477. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  68478. __decorate([
  68479. BABYLON.serializeAsTexture("lensTexture")
  68480. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  68481. __decorate([
  68482. BABYLON.serialize()
  68483. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  68484. __decorate([
  68485. BABYLON.serialize()
  68486. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  68487. __decorate([
  68488. BABYLON.serialize()
  68489. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  68490. __decorate([
  68491. BABYLON.serialize()
  68492. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  68493. __decorate([
  68494. BABYLON.serialize()
  68495. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  68496. __decorate([
  68497. BABYLON.serialize()
  68498. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  68499. __decorate([
  68500. BABYLON.serializeAsTexture("lensColorTexture")
  68501. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  68502. __decorate([
  68503. BABYLON.serialize()
  68504. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  68505. __decorate([
  68506. BABYLON.serialize()
  68507. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  68508. __decorate([
  68509. BABYLON.serialize()
  68510. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  68511. __decorate([
  68512. BABYLON.serialize()
  68513. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  68514. __decorate([
  68515. BABYLON.serializeAsTexture("lensStarTexture")
  68516. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  68517. __decorate([
  68518. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  68519. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  68520. __decorate([
  68521. BABYLON.serialize()
  68522. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  68523. __decorate([
  68524. BABYLON.serialize()
  68525. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  68526. __decorate([
  68527. BABYLON.serialize()
  68528. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  68529. __decorate([
  68530. BABYLON.serialize()
  68531. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  68532. __decorate([
  68533. BABYLON.serialize()
  68534. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  68535. __decorate([
  68536. BABYLON.serialize()
  68537. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  68538. __decorate([
  68539. BABYLON.serialize()
  68540. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  68541. __decorate([
  68542. BABYLON.serialize()
  68543. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  68544. __decorate([
  68545. BABYLON.serialize()
  68546. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  68547. __decorate([
  68548. BABYLON.serialize()
  68549. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  68550. __decorate([
  68551. BABYLON.serialize()
  68552. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  68553. __decorate([
  68554. BABYLON.serialize()
  68555. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  68556. return StandardRenderingPipeline;
  68557. }(BABYLON.PostProcessRenderPipeline));
  68558. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  68559. })(BABYLON || (BABYLON = {}));
  68560. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  68561. var BABYLON;
  68562. (function (BABYLON) {
  68563. var FxaaPostProcess = /** @class */ (function (_super) {
  68564. __extends(FxaaPostProcess, _super);
  68565. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68566. if (camera === void 0) { camera = null; }
  68567. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68568. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  68569. _this.onApplyObservable.add(function (effect) {
  68570. var texelSize = _this.texelSize;
  68571. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  68572. });
  68573. return _this;
  68574. }
  68575. return FxaaPostProcess;
  68576. }(BABYLON.PostProcess));
  68577. BABYLON.FxaaPostProcess = FxaaPostProcess;
  68578. })(BABYLON || (BABYLON = {}));
  68579. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  68580. var BABYLON;
  68581. (function (BABYLON) {
  68582. /**
  68583. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  68584. */
  68585. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  68586. __extends(ChromaticAberrationPostProcess, _super);
  68587. /**
  68588. * Creates a new instance of @see ChromaticAberrationPostProcess
  68589. * @param name The name of the effect.
  68590. * @param screenWidth The width of the screen to apply the effect on.
  68591. * @param screenHeight The height of the screen to apply the effect on.
  68592. * @param options The required width/height ratio to downsize to before computing the render pass.
  68593. * @param camera The camera to apply the render pass to.
  68594. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68595. * @param engine The engine which the post process will be applied. (default: current engine)
  68596. * @param reusable If the post process can be reused on the same frame. (default: false)
  68597. * @param textureType Type of textures used when performing the post process. (default: 0)
  68598. * @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)
  68599. */
  68600. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68601. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68602. if (blockCompilation === void 0) { blockCompilation = false; }
  68603. 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;
  68604. /**
  68605. * The amount of seperation of rgb channels (default: 0)
  68606. */
  68607. _this.aberrationAmount = 0;
  68608. /**
  68609. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  68610. */
  68611. _this.radialIntensity = 0;
  68612. /**
  68613. * 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))
  68614. */
  68615. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  68616. /**
  68617. * 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))
  68618. */
  68619. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  68620. _this.onApplyObservable.add(function (effect) {
  68621. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  68622. effect.setFloat('screen_width', screenWidth);
  68623. effect.setFloat('screen_height', screenHeight);
  68624. effect.setFloat('radialIntensity', _this.radialIntensity);
  68625. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  68626. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  68627. });
  68628. return _this;
  68629. }
  68630. return ChromaticAberrationPostProcess;
  68631. }(BABYLON.PostProcess));
  68632. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  68633. })(BABYLON || (BABYLON = {}));
  68634. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  68635. var BABYLON;
  68636. (function (BABYLON) {
  68637. /**
  68638. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68639. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68640. */
  68641. var SharpenPostProcess = /** @class */ (function (_super) {
  68642. __extends(SharpenPostProcess, _super);
  68643. /**
  68644. * Creates a new instance of @see ConvolutionPostProcess
  68645. * @param name The name of the effect.
  68646. * @param options The required width/height ratio to downsize to before computing the render pass.
  68647. * @param camera The camera to apply the render pass to.
  68648. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68649. * @param engine The engine which the post process will be applied. (default: current engine)
  68650. * @param reusable If the post process can be reused on the same frame. (default: false)
  68651. * @param textureType Type of textures used when performing the post process. (default: 0)
  68652. * @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)
  68653. */
  68654. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68655. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68656. if (blockCompilation === void 0) { blockCompilation = false; }
  68657. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68658. /**
  68659. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68660. */
  68661. _this.colorAmount = 1.0;
  68662. /**
  68663. * How much sharpness should be applied (default: 0.3)
  68664. */
  68665. _this.edgeAmount = 0.3;
  68666. _this.onApply = function (effect) {
  68667. effect.setFloat2("screenSize", _this.width, _this.height);
  68668. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68669. };
  68670. return _this;
  68671. }
  68672. return SharpenPostProcess;
  68673. }(BABYLON.PostProcess));
  68674. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68675. })(BABYLON || (BABYLON = {}));
  68676. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68677. var BABYLON;
  68678. (function (BABYLON) {
  68679. /**
  68680. * The Blur Post Process which blurs an image based on a kernel and direction.
  68681. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68682. */
  68683. var BlurPostProcess = /** @class */ (function (_super) {
  68684. __extends(BlurPostProcess, _super);
  68685. /**
  68686. * Creates a new instance of @see BlurPostProcess
  68687. * @param name The name of the effect.
  68688. * @param direction The direction in which to blur the image.
  68689. * @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.
  68690. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68691. * @param camera The camera to apply the render pass to.
  68692. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68693. * @param engine The engine which the post process will be applied. (default: current engine)
  68694. * @param reusable If the post process can be reused on the same frame. (default: false)
  68695. * @param textureType Type of textures used when performing the post process. (default: 0)
  68696. * @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)
  68697. */
  68698. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  68699. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68700. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68701. if (defines === void 0) { defines = ""; }
  68702. if (blockCompilation === void 0) { blockCompilation = false; }
  68703. 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;
  68704. _this.direction = direction;
  68705. _this.blockCompilation = blockCompilation;
  68706. _this._packedFloat = false;
  68707. _this._staticDefines = "";
  68708. _this._staticDefines = defines;
  68709. _this.onApplyObservable.add(function (effect) {
  68710. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68711. });
  68712. _this.kernel = kernel;
  68713. return _this;
  68714. }
  68715. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68716. /**
  68717. * Gets the length in pixels of the blur sample region
  68718. */
  68719. get: function () {
  68720. return this._idealKernel;
  68721. },
  68722. /**
  68723. * Sets the length in pixels of the blur sample region
  68724. */
  68725. set: function (v) {
  68726. if (this._idealKernel === v) {
  68727. return;
  68728. }
  68729. v = Math.max(v, 1);
  68730. this._idealKernel = v;
  68731. this._kernel = this._nearestBestKernel(v);
  68732. if (!this.blockCompilation) {
  68733. this._updateParameters();
  68734. }
  68735. },
  68736. enumerable: true,
  68737. configurable: true
  68738. });
  68739. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68740. /**
  68741. * Gets wether or not the blur is unpacking/repacking floats
  68742. */
  68743. get: function () {
  68744. return this._packedFloat;
  68745. },
  68746. /**
  68747. * Sets wether or not the blur needs to unpack/repack floats
  68748. */
  68749. set: function (v) {
  68750. if (this._packedFloat === v) {
  68751. return;
  68752. }
  68753. this._packedFloat = v;
  68754. if (!this.blockCompilation) {
  68755. this._updateParameters();
  68756. }
  68757. },
  68758. enumerable: true,
  68759. configurable: true
  68760. });
  68761. /**
  68762. * Updates the effect with the current post process compile time values and recompiles the shader.
  68763. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68764. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68765. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68766. * @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
  68767. * @param onCompiled Called when the shader has been compiled.
  68768. * @param onError Called if there is an error when compiling a shader.
  68769. */
  68770. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68771. if (defines === void 0) { defines = null; }
  68772. if (uniforms === void 0) { uniforms = null; }
  68773. if (samplers === void 0) { samplers = null; }
  68774. this._updateParameters(onCompiled, onError);
  68775. };
  68776. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  68777. // Generate sampling offsets and weights
  68778. var N = this._kernel;
  68779. var centerIndex = (N - 1) / 2;
  68780. // Generate Gaussian sampling weights over kernel
  68781. var offsets = [];
  68782. var weights = [];
  68783. var totalWeight = 0;
  68784. for (var i = 0; i < N; i++) {
  68785. var u = i / (N - 1);
  68786. var w = this._gaussianWeight(u * 2.0 - 1);
  68787. offsets[i] = (i - centerIndex);
  68788. weights[i] = w;
  68789. totalWeight += w;
  68790. }
  68791. // Normalize weights
  68792. for (var i = 0; i < weights.length; i++) {
  68793. weights[i] /= totalWeight;
  68794. }
  68795. // Optimize: combine samples to take advantage of hardware linear sampling
  68796. // Walk from left to center, combining pairs (symmetrically)
  68797. var linearSamplingWeights = [];
  68798. var linearSamplingOffsets = [];
  68799. var linearSamplingMap = [];
  68800. for (var i = 0; i <= centerIndex; i += 2) {
  68801. var j = Math.min(i + 1, Math.floor(centerIndex));
  68802. var singleCenterSample = i === j;
  68803. if (singleCenterSample) {
  68804. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68805. }
  68806. else {
  68807. var sharedCell = j === centerIndex;
  68808. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68809. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68810. if (offsetLinear === 0) {
  68811. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68812. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68813. }
  68814. else {
  68815. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68816. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68817. }
  68818. }
  68819. }
  68820. for (var i = 0; i < linearSamplingMap.length; i++) {
  68821. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68822. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68823. }
  68824. // Replace with optimized
  68825. offsets = linearSamplingOffsets;
  68826. weights = linearSamplingWeights;
  68827. // Generate shaders
  68828. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68829. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68830. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68831. var defines = "";
  68832. defines += this._staticDefines;
  68833. for (var i = 0; i < varyingCount; i++) {
  68834. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68835. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68836. }
  68837. var depCount = 0;
  68838. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68839. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68840. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68841. depCount++;
  68842. }
  68843. if (this.packedFloat) {
  68844. defines += "#define PACKEDFLOAT 1";
  68845. }
  68846. _super.prototype.updateEffect.call(this, defines, null, null, {
  68847. varyingCount: varyingCount,
  68848. depCount: depCount
  68849. }, onCompiled, onError);
  68850. };
  68851. /**
  68852. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68853. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68854. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68855. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68856. * The gaps between physical kernels are compensated for in the weighting of the samples
  68857. * @param idealKernel Ideal blur kernel.
  68858. * @return Nearest best kernel.
  68859. */
  68860. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68861. var v = Math.round(idealKernel);
  68862. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68863. var k = _a[_i];
  68864. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68865. return Math.max(k, 3);
  68866. }
  68867. }
  68868. return Math.max(v, 3);
  68869. };
  68870. /**
  68871. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68872. * @param x The point on the Gaussian distribution to sample.
  68873. * @return the value of the Gaussian function at x.
  68874. */
  68875. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68876. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68877. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68878. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68879. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68880. // truncated at around 1.3% of peak strength.
  68881. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68882. var sigma = (1 / 3);
  68883. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68884. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68885. var weight = (1.0 / denominator) * Math.exp(exponent);
  68886. return weight;
  68887. };
  68888. /**
  68889. * Generates a string that can be used as a floating point number in GLSL.
  68890. * @param x Value to print.
  68891. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68892. * @return GLSL float string.
  68893. */
  68894. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68895. if (decimalFigures === void 0) { decimalFigures = 8; }
  68896. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68897. };
  68898. return BlurPostProcess;
  68899. }(BABYLON.PostProcess));
  68900. BABYLON.BlurPostProcess = BlurPostProcess;
  68901. })(BABYLON || (BABYLON = {}));
  68902. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68903. var BABYLON;
  68904. (function (BABYLON) {
  68905. /**
  68906. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  68907. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  68908. * based on samples that have a large difference in distance than the center pixel.
  68909. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68910. */
  68911. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  68912. __extends(DepthOfFieldBlurPostProcess, _super);
  68913. /**
  68914. * Creates a new instance of @see CircleOfConfusionPostProcess
  68915. * @param name The name of the effect.
  68916. * @param scene The scene the effect belongs to.
  68917. * @param direction The direction the blur should be applied.
  68918. * @param kernel The size of the kernel used to blur.
  68919. * @param options The required width/height ratio to downsize to before computing the render pass.
  68920. * @param camera The camera to apply the render pass to.
  68921. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  68922. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  68923. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68924. * @param engine The engine which the post process will be applied. (default: current engine)
  68925. * @param reusable If the post process can be reused on the same frame. (default: false)
  68926. * @param textureType Type of textures used when performing the post process. (default: 0)
  68927. * @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)
  68928. */
  68929. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  68930. if (imageToBlur === void 0) { imageToBlur = null; }
  68931. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68932. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68933. if (blockCompilation === void 0) { blockCompilation = false; }
  68934. 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;
  68935. _this.direction = direction;
  68936. _this.onApplyObservable.add(function (effect) {
  68937. if (imageToBlur != null) {
  68938. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  68939. }
  68940. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68941. if (scene.activeCamera) {
  68942. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  68943. }
  68944. });
  68945. return _this;
  68946. }
  68947. return DepthOfFieldBlurPostProcess;
  68948. }(BABYLON.BlurPostProcess));
  68949. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  68950. })(BABYLON || (BABYLON = {}));
  68951. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  68952. var BABYLON;
  68953. (function (BABYLON) {
  68954. /**
  68955. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  68956. */
  68957. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  68958. __extends(DepthOfFieldMergePostProcess, _super);
  68959. /**
  68960. * Creates a new instance of @see CircleOfConfusionPostProcess
  68961. * @param name The name of the effect.
  68962. * @param original The non-blurred image to be modified
  68963. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  68964. * @param blurSteps Incrimental bluring post processes.
  68965. * @param options The required width/height ratio to downsize to before computing the render pass.
  68966. * @param camera The camera to apply the render pass to.
  68967. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68968. * @param engine The engine which the post process will be applied. (default: current engine)
  68969. * @param reusable If the post process can be reused on the same frame. (default: false)
  68970. * @param textureType Type of textures used when performing the post process. (default: 0)
  68971. * @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)
  68972. */
  68973. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68974. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68975. if (blockCompilation === void 0) { blockCompilation = false; }
  68976. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  68977. _this.blurSteps = blurSteps;
  68978. _this.onApplyObservable.add(function (effect) {
  68979. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68980. effect.setTextureFromPostProcess("originalSampler", original);
  68981. blurSteps.forEach(function (step, index) {
  68982. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  68983. });
  68984. });
  68985. if (!blockCompilation) {
  68986. _this.updateEffect();
  68987. }
  68988. return _this;
  68989. }
  68990. /**
  68991. * Updates the effect with the current post process compile time values and recompiles the shader.
  68992. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68993. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68994. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68995. * @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
  68996. * @param onCompiled Called when the shader has been compiled.
  68997. * @param onError Called if there is an error when compiling a shader.
  68998. */
  68999. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69000. if (defines === void 0) { defines = null; }
  69001. if (uniforms === void 0) { uniforms = null; }
  69002. if (samplers === void 0) { samplers = null; }
  69003. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + this.blurSteps.length + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  69004. };
  69005. return DepthOfFieldMergePostProcess;
  69006. }(BABYLON.PostProcess));
  69007. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  69008. })(BABYLON || (BABYLON = {}));
  69009. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  69010. var BABYLON;
  69011. (function (BABYLON) {
  69012. /**
  69013. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  69014. */
  69015. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  69016. __extends(CircleOfConfusionPostProcess, _super);
  69017. /**
  69018. * Creates a new instance of @see CircleOfConfusionPostProcess
  69019. * @param name The name of the effect.
  69020. * @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.
  69021. * @param options The required width/height ratio to downsize to before computing the render pass.
  69022. * @param camera The camera to apply the render pass to.
  69023. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69024. * @param engine The engine which the post process will be applied. (default: current engine)
  69025. * @param reusable If the post process can be reused on the same frame. (default: false)
  69026. * @param textureType Type of textures used when performing the post process. (default: 0)
  69027. * @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)
  69028. */
  69029. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69030. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69031. if (blockCompilation === void 0) { blockCompilation = false; }
  69032. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69033. /**
  69034. * 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.
  69035. */
  69036. _this.lensSize = 50;
  69037. /**
  69038. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69039. */
  69040. _this.fStop = 1.4;
  69041. /**
  69042. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69043. */
  69044. _this.focusDistance = 2000;
  69045. /**
  69046. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  69047. */
  69048. _this.focalLength = 50;
  69049. _this._depthTexture = null;
  69050. _this._depthTexture = depthTexture;
  69051. _this.onApplyObservable.add(function (effect) {
  69052. if (!_this._depthTexture) {
  69053. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  69054. return;
  69055. }
  69056. effect.setTexture("depthSampler", _this._depthTexture);
  69057. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  69058. var aperture = _this.lensSize / _this.fStop;
  69059. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  69060. effect.setFloat('focusDistance', _this.focusDistance);
  69061. effect.setFloat('cocPrecalculation', cocPrecalculation);
  69062. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  69063. });
  69064. return _this;
  69065. }
  69066. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  69067. /**
  69068. * 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.
  69069. */
  69070. set: function (value) {
  69071. this._depthTexture = value;
  69072. },
  69073. enumerable: true,
  69074. configurable: true
  69075. });
  69076. return CircleOfConfusionPostProcess;
  69077. }(BABYLON.PostProcess));
  69078. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  69079. })(BABYLON || (BABYLON = {}));
  69080. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  69081. var BABYLON;
  69082. (function (BABYLON) {
  69083. /**
  69084. * Specifies the level of max blur that should be applied when using the depth of field effect
  69085. */
  69086. var DepthOfFieldEffectBlurLevel;
  69087. (function (DepthOfFieldEffectBlurLevel) {
  69088. /**
  69089. * Subtle blur
  69090. */
  69091. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  69092. /**
  69093. * Medium blur
  69094. */
  69095. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  69096. /**
  69097. * Large blur
  69098. */
  69099. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  69100. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  69101. ;
  69102. /**
  69103. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  69104. */
  69105. var DepthOfFieldEffect = /** @class */ (function (_super) {
  69106. __extends(DepthOfFieldEffect, _super);
  69107. /**
  69108. * Creates a new instance of @see DepthOfFieldEffect
  69109. * @param scene The scene the effect belongs to.
  69110. * @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.
  69111. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  69112. * @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)
  69113. */
  69114. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  69115. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  69116. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  69117. if (blockCompilation === void 0) { blockCompilation = false; }
  69118. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  69119. return _this._effects;
  69120. }, true) || this;
  69121. _this._effects = [];
  69122. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  69123. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69124. // Capture circle of confusion texture
  69125. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69126. _this._depthOfFieldPass.autoClear = false;
  69127. // 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)
  69128. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  69129. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69130. _this._depthOfFieldBlurY = [];
  69131. _this._depthOfFieldBlurX = [];
  69132. var blurCount = 1;
  69133. var kernelSize = 15;
  69134. switch (blurLevel) {
  69135. case DepthOfFieldEffectBlurLevel.High: {
  69136. blurCount = 3;
  69137. kernelSize = 51;
  69138. break;
  69139. }
  69140. case DepthOfFieldEffectBlurLevel.Medium: {
  69141. blurCount = 2;
  69142. kernelSize = 31;
  69143. break;
  69144. }
  69145. default: {
  69146. kernelSize = 15;
  69147. blurCount = 1;
  69148. break;
  69149. }
  69150. }
  69151. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  69152. for (var i = 0; i < blurCount; i++) {
  69153. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69154. blurY.autoClear = false;
  69155. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69156. blurX.autoClear = false;
  69157. _this._depthOfFieldBlurY.push(blurY);
  69158. _this._depthOfFieldBlurX.push(blurX);
  69159. }
  69160. // Merge blurred images with original image based on circleOfConfusion
  69161. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69162. _this._depthOfFieldMerge.autoClear = false;
  69163. // Set all post processes on the effect.
  69164. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  69165. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  69166. _this._effects.push(_this._depthOfFieldBlurY[i]);
  69167. _this._effects.push(_this._depthOfFieldBlurX[i]);
  69168. }
  69169. _this._effects.push(_this._depthOfFieldMerge);
  69170. return _this;
  69171. }
  69172. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  69173. get: function () {
  69174. return this._circleOfConfusion.focalLength;
  69175. },
  69176. /**
  69177. * The focal the length of the camera used in the effect
  69178. */
  69179. set: function (value) {
  69180. this._circleOfConfusion.focalLength = value;
  69181. },
  69182. enumerable: true,
  69183. configurable: true
  69184. });
  69185. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  69186. get: function () {
  69187. return this._circleOfConfusion.fStop;
  69188. },
  69189. /**
  69190. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69191. */
  69192. set: function (value) {
  69193. this._circleOfConfusion.fStop = value;
  69194. },
  69195. enumerable: true,
  69196. configurable: true
  69197. });
  69198. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  69199. get: function () {
  69200. return this._circleOfConfusion.focusDistance;
  69201. },
  69202. /**
  69203. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69204. */
  69205. set: function (value) {
  69206. this._circleOfConfusion.focusDistance = value;
  69207. },
  69208. enumerable: true,
  69209. configurable: true
  69210. });
  69211. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  69212. get: function () {
  69213. return this._circleOfConfusion.lensSize;
  69214. },
  69215. /**
  69216. * 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.
  69217. */
  69218. set: function (value) {
  69219. this._circleOfConfusion.lensSize = value;
  69220. },
  69221. enumerable: true,
  69222. configurable: true
  69223. });
  69224. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  69225. /**
  69226. * 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.
  69227. */
  69228. set: function (value) {
  69229. this._circleOfConfusion.depthTexture = value;
  69230. },
  69231. enumerable: true,
  69232. configurable: true
  69233. });
  69234. /**
  69235. * Disposes each of the internal effects for a given camera.
  69236. * @param camera The camera to dispose the effect on.
  69237. */
  69238. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  69239. this._depthOfFieldPass.dispose(camera);
  69240. this._circleOfConfusion.dispose(camera);
  69241. this._depthOfFieldBlurX.forEach(function (element) {
  69242. element.dispose(camera);
  69243. });
  69244. this._depthOfFieldBlurY.forEach(function (element) {
  69245. element.dispose(camera);
  69246. });
  69247. this._depthOfFieldMerge.dispose(camera);
  69248. };
  69249. /**
  69250. * Internal
  69251. */
  69252. DepthOfFieldEffect.prototype._updateEffects = function () {
  69253. for (var effect in this._effects) {
  69254. this._effects[effect].updateEffect();
  69255. }
  69256. };
  69257. /**
  69258. * Internal
  69259. * @returns if all the contained post processes are ready.
  69260. */
  69261. DepthOfFieldEffect.prototype._isReady = function () {
  69262. for (var effect in this._effects) {
  69263. if (!this._effects[effect].isReady()) {
  69264. return false;
  69265. }
  69266. }
  69267. return true;
  69268. };
  69269. return DepthOfFieldEffect;
  69270. }(BABYLON.PostProcessRenderEffect));
  69271. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  69272. })(BABYLON || (BABYLON = {}));
  69273. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  69274. var BABYLON;
  69275. (function (BABYLON) {
  69276. /**
  69277. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  69278. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  69279. */
  69280. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  69281. __extends(DefaultRenderingPipeline, _super);
  69282. /**
  69283. * @constructor
  69284. * @param {string} name - The rendering pipeline name
  69285. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69286. * @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)
  69287. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69288. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  69289. */
  69290. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  69291. if (automaticBuild === void 0) { automaticBuild = true; }
  69292. var _this = _super.call(this, scene.getEngine(), name) || this;
  69293. _this._originalCameras = [];
  69294. /**
  69295. * ID of the sharpen post process,
  69296. */
  69297. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  69298. /**
  69299. * ID of the pass post process used for bloom,
  69300. */
  69301. _this.PassPostProcessId = "PassPostProcessEffect";
  69302. /**
  69303. * ID of the highlight post process used for bloom,
  69304. */
  69305. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  69306. /**
  69307. * ID of the blurX post process used for bloom,
  69308. */
  69309. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  69310. /**
  69311. * ID of the blurY post process used for bloom,
  69312. */
  69313. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  69314. /**
  69315. * ID of the copy back post process used for bloom,
  69316. */
  69317. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  69318. /**
  69319. * ID of the image processing post process;
  69320. */
  69321. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  69322. /**
  69323. * ID of the Fast Approximate Anti-Aliasing post process;
  69324. */
  69325. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  69326. /**
  69327. * ID of the final merge post process;
  69328. */
  69329. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  69330. /**
  69331. * ID of the chromatic aberration post process,
  69332. */
  69333. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  69334. /**
  69335. * Animations which can be used to tweak settings over a period of time
  69336. */
  69337. _this.animations = [];
  69338. // Values
  69339. _this._sharpenEnabled = false;
  69340. _this._bloomEnabled = false;
  69341. _this._depthOfFieldEnabled = false;
  69342. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  69343. _this._fxaaEnabled = false;
  69344. _this._msaaEnabled = false;
  69345. _this._imageProcessingEnabled = true;
  69346. _this._bloomScale = 0.6;
  69347. _this._chromaticAberrationEnabled = false;
  69348. _this._buildAllowed = true;
  69349. /**
  69350. * Specifies the size of the bloom blur kernel, relative to the final output size
  69351. */
  69352. _this.bloomKernel = 64;
  69353. /**
  69354. * Specifies the weight of the bloom in the final rendering
  69355. */
  69356. _this._bloomWeight = 0.15;
  69357. _this._prevPostProcess = null;
  69358. _this._prevPrevPostProcess = null;
  69359. _this._cameras = cameras || [];
  69360. _this._originalCameras = _this._cameras.slice();
  69361. _this._buildAllowed = automaticBuild;
  69362. // Initialize
  69363. _this._scene = scene;
  69364. var caps = _this._scene.getEngine().getCaps();
  69365. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  69366. // Misc
  69367. if (_this._hdr) {
  69368. if (caps.textureHalfFloatRender) {
  69369. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69370. }
  69371. else if (caps.textureFloatRender) {
  69372. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69373. }
  69374. }
  69375. else {
  69376. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69377. }
  69378. // Attach
  69379. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69380. var engine = _this._scene.getEngine();
  69381. // Create post processes before hand so they can be modified before enabled.
  69382. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  69383. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69384. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  69385. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  69386. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69387. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  69388. _this._buildPipeline();
  69389. return _this;
  69390. }
  69391. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  69392. get: function () {
  69393. return this._sharpenEnabled;
  69394. },
  69395. /**
  69396. * Enable or disable the sharpen process from the pipeline
  69397. */
  69398. set: function (enabled) {
  69399. if (this._sharpenEnabled === enabled) {
  69400. return;
  69401. }
  69402. this._sharpenEnabled = enabled;
  69403. this._buildPipeline();
  69404. },
  69405. enumerable: true,
  69406. configurable: true
  69407. });
  69408. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  69409. get: function () {
  69410. return this._bloomWeight;
  69411. },
  69412. /**
  69413. * The strength of the bloom.
  69414. */
  69415. set: function (value) {
  69416. if (this._bloomWeight === value) {
  69417. return;
  69418. }
  69419. this._bloomWeight = value;
  69420. if (this._hdr && this.copyBack) {
  69421. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  69422. }
  69423. },
  69424. enumerable: true,
  69425. configurable: true
  69426. });
  69427. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  69428. get: function () {
  69429. return this._bloomScale;
  69430. },
  69431. /**
  69432. * The scale of the bloom, lower value will provide better performance.
  69433. */
  69434. set: function (value) {
  69435. if (this._bloomScale === value) {
  69436. return;
  69437. }
  69438. this._bloomScale = value;
  69439. this._buildPipeline();
  69440. },
  69441. enumerable: true,
  69442. configurable: true
  69443. });
  69444. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  69445. get: function () {
  69446. return this._bloomEnabled;
  69447. },
  69448. /**
  69449. * Enable or disable the bloom from the pipeline
  69450. */
  69451. set: function (enabled) {
  69452. if (this._bloomEnabled === enabled) {
  69453. return;
  69454. }
  69455. this._bloomEnabled = enabled;
  69456. this._buildPipeline();
  69457. },
  69458. enumerable: true,
  69459. configurable: true
  69460. });
  69461. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  69462. /**
  69463. * If the depth of field is enabled.
  69464. */
  69465. get: function () {
  69466. return this._depthOfFieldEnabled;
  69467. },
  69468. set: function (enabled) {
  69469. if (this._depthOfFieldEnabled === enabled) {
  69470. return;
  69471. }
  69472. this._depthOfFieldEnabled = enabled;
  69473. this._buildPipeline();
  69474. },
  69475. enumerable: true,
  69476. configurable: true
  69477. });
  69478. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  69479. /**
  69480. * Blur level of the depth of field effect. (Higher blur will effect performance)
  69481. */
  69482. get: function () {
  69483. return this._depthOfFieldBlurLevel;
  69484. },
  69485. set: function (value) {
  69486. if (this._depthOfFieldBlurLevel === value) {
  69487. return;
  69488. }
  69489. this._depthOfFieldBlurLevel = value;
  69490. // recreate dof and dispose old as this setting is not dynamic
  69491. var oldDof = this.depthOfField;
  69492. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  69493. this.depthOfField.focalLength = oldDof.focalLength;
  69494. this.depthOfField.focusDistance = oldDof.focusDistance;
  69495. this.depthOfField.fStop = oldDof.fStop;
  69496. this.depthOfField.lensSize = oldDof.lensSize;
  69497. for (var i = 0; i < this._cameras.length; i++) {
  69498. oldDof.disposeEffects(this._cameras[i]);
  69499. }
  69500. this._buildPipeline();
  69501. },
  69502. enumerable: true,
  69503. configurable: true
  69504. });
  69505. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  69506. get: function () {
  69507. return this._fxaaEnabled;
  69508. },
  69509. /**
  69510. * If the anti aliasing is enabled.
  69511. */
  69512. set: function (enabled) {
  69513. if (this._fxaaEnabled === enabled) {
  69514. return;
  69515. }
  69516. this._fxaaEnabled = enabled;
  69517. this._buildPipeline();
  69518. },
  69519. enumerable: true,
  69520. configurable: true
  69521. });
  69522. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  69523. get: function () {
  69524. return this._msaaEnabled;
  69525. },
  69526. /**
  69527. * If the multisample anti-aliasing is enabled.
  69528. */
  69529. set: function (enabled) {
  69530. if (this._msaaEnabled === enabled) {
  69531. return;
  69532. }
  69533. this._msaaEnabled = enabled;
  69534. this._buildPipeline();
  69535. },
  69536. enumerable: true,
  69537. configurable: true
  69538. });
  69539. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  69540. get: function () {
  69541. return this._imageProcessingEnabled;
  69542. },
  69543. /**
  69544. * If image processing is enabled.
  69545. */
  69546. set: function (enabled) {
  69547. if (this._imageProcessingEnabled === enabled) {
  69548. return;
  69549. }
  69550. this._imageProcessingEnabled = enabled;
  69551. this._buildPipeline();
  69552. },
  69553. enumerable: true,
  69554. configurable: true
  69555. });
  69556. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  69557. get: function () {
  69558. return this._chromaticAberrationEnabled;
  69559. },
  69560. /**
  69561. * Enable or disable the chromaticAberration process from the pipeline
  69562. */
  69563. set: function (enabled) {
  69564. if (this._chromaticAberrationEnabled === enabled) {
  69565. return;
  69566. }
  69567. this._chromaticAberrationEnabled = enabled;
  69568. this._buildPipeline();
  69569. },
  69570. enumerable: true,
  69571. configurable: true
  69572. });
  69573. /**
  69574. * Force the compilation of the entire pipeline.
  69575. */
  69576. DefaultRenderingPipeline.prototype.prepare = function () {
  69577. var previousState = this._buildAllowed;
  69578. this._buildAllowed = true;
  69579. this._buildPipeline();
  69580. this._buildAllowed = previousState;
  69581. };
  69582. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  69583. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  69584. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  69585. postProcess.autoClear = false;
  69586. }
  69587. else {
  69588. postProcess.autoClear = true;
  69589. }
  69590. if (!skipTextureSharing) {
  69591. if (this._prevPrevPostProcess) {
  69592. postProcess.shareOutputWith(this._prevPrevPostProcess);
  69593. }
  69594. else {
  69595. postProcess.useOwnOutput();
  69596. }
  69597. if (this._prevPostProcess) {
  69598. this._prevPrevPostProcess = this._prevPostProcess;
  69599. }
  69600. this._prevPostProcess = postProcess;
  69601. }
  69602. };
  69603. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  69604. var _this = this;
  69605. if (!this._buildAllowed) {
  69606. return;
  69607. }
  69608. var engine = this._scene.getEngine();
  69609. this._disposePostProcesses();
  69610. if (this._cameras !== null) {
  69611. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69612. // get back cameras to be used to reattach pipeline
  69613. this._cameras = this._originalCameras.slice();
  69614. }
  69615. this._reset();
  69616. this._prevPostProcess = null;
  69617. this._prevPrevPostProcess = null;
  69618. if (this.sharpenEnabled) {
  69619. if (!this.sharpen.isReady()) {
  69620. this.sharpen.updateEffect();
  69621. }
  69622. this.addEffect(this._sharpenEffect);
  69623. this._setAutoClearAndTextureSharing(this.sharpen);
  69624. }
  69625. if (this.depthOfFieldEnabled) {
  69626. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  69627. this.depthOfField.depthTexture = depthTexture;
  69628. if (!this.depthOfField._isReady()) {
  69629. this.depthOfField._updateEffects();
  69630. }
  69631. this.addEffect(this.depthOfField);
  69632. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  69633. }
  69634. if (this.bloomEnabled) {
  69635. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69636. this._setAutoClearAndTextureSharing(this.pass, true);
  69637. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  69638. if (!this._hdr) {
  69639. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69640. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  69641. this.highlights.autoClear = false;
  69642. this.highlights.alwaysForcePOT = true;
  69643. }
  69644. 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);
  69645. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  69646. this.blurX.alwaysForcePOT = true;
  69647. this.blurX.autoClear = false;
  69648. this.blurX.onActivateObservable.add(function () {
  69649. var dw = _this.blurX.width / engine.getRenderWidth(true);
  69650. _this.blurX.kernel = _this.bloomKernel * dw;
  69651. });
  69652. 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);
  69653. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  69654. this.blurY.alwaysForcePOT = true;
  69655. this.blurY.autoClear = false;
  69656. this.blurY.onActivateObservable.add(function () {
  69657. var dh = _this.blurY.height / engine.getRenderHeight(true);
  69658. _this.blurY.kernel = _this.bloomKernel * dh;
  69659. });
  69660. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69661. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  69662. this.copyBack.alwaysForcePOT = true;
  69663. if (this._hdr) {
  69664. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  69665. var w = this.bloomWeight;
  69666. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  69667. }
  69668. else {
  69669. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  69670. }
  69671. this.copyBack.autoClear = false;
  69672. }
  69673. if (this._imageProcessingEnabled) {
  69674. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69675. if (this._hdr) {
  69676. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  69677. }
  69678. else {
  69679. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  69680. }
  69681. }
  69682. if (this._hdr && this.imageProcessing) {
  69683. this.finalMerge = this.imageProcessing;
  69684. }
  69685. else {
  69686. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69687. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  69688. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  69689. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  69690. }
  69691. if (this.bloomEnabled) {
  69692. if (this._hdr) {
  69693. this.copyBack.shareOutputWith(this.blurX);
  69694. if (this.imageProcessing) {
  69695. this.imageProcessing.shareOutputWith(this.pass);
  69696. this.imageProcessing.autoClear = false;
  69697. }
  69698. else {
  69699. this.finalMerge.shareOutputWith(this.pass);
  69700. }
  69701. }
  69702. else {
  69703. this.finalMerge.shareOutputWith(this.pass);
  69704. }
  69705. }
  69706. if (this.fxaaEnabled) {
  69707. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69708. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  69709. this._setAutoClearAndTextureSharing(this.fxaa);
  69710. }
  69711. if (this.chromaticAberrationEnabled) {
  69712. if (!this.chromaticAberration.isReady()) {
  69713. this.chromaticAberration.updateEffect();
  69714. }
  69715. this.addEffect(this._chromaticAberrationEffect);
  69716. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  69717. }
  69718. if (this._cameras !== null) {
  69719. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69720. }
  69721. if (this.msaaEnabled) {
  69722. if (!this._enableMSAAOnFirstPostProcess()) {
  69723. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  69724. }
  69725. }
  69726. };
  69727. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  69728. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  69729. for (var i = 0; i < this._cameras.length; i++) {
  69730. var camera = this._cameras[i];
  69731. if (this.pass) {
  69732. this.pass.dispose(camera);
  69733. }
  69734. if (this.highlights) {
  69735. this.highlights.dispose(camera);
  69736. }
  69737. if (this.blurX) {
  69738. this.blurX.dispose(camera);
  69739. }
  69740. if (this.blurY) {
  69741. this.blurY.dispose(camera);
  69742. }
  69743. if (this.copyBack) {
  69744. this.copyBack.dispose(camera);
  69745. }
  69746. if (this.imageProcessing) {
  69747. this.imageProcessing.dispose(camera);
  69748. }
  69749. if (this.fxaa) {
  69750. this.fxaa.dispose(camera);
  69751. }
  69752. if (this.finalMerge) {
  69753. this.finalMerge.dispose(camera);
  69754. }
  69755. // These are created in the constructor and should not be disposed on every pipeline change
  69756. if (disposeNonRecreated) {
  69757. if (this.sharpen) {
  69758. this.sharpen.dispose(camera);
  69759. }
  69760. if (this.depthOfField) {
  69761. this.depthOfField.disposeEffects(camera);
  69762. }
  69763. if (this.chromaticAberration) {
  69764. this.chromaticAberration.dispose(camera);
  69765. }
  69766. }
  69767. }
  69768. this.pass = null;
  69769. this.highlights = null;
  69770. this.blurX = null;
  69771. this.blurY = null;
  69772. this.copyBack = null;
  69773. this.imageProcessing = null;
  69774. this.fxaa = null;
  69775. this.finalMerge = null;
  69776. if (disposeNonRecreated) {
  69777. this.sharpen = null;
  69778. this.depthOfField = null;
  69779. this.chromaticAberration = null;
  69780. }
  69781. };
  69782. /**
  69783. * Dispose of the pipeline and stop all post processes
  69784. */
  69785. DefaultRenderingPipeline.prototype.dispose = function () {
  69786. this._disposePostProcesses(true);
  69787. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69788. _super.prototype.dispose.call(this);
  69789. };
  69790. /**
  69791. * Serialize the rendering pipeline (Used when exporting)
  69792. * @returns the serialized object
  69793. */
  69794. DefaultRenderingPipeline.prototype.serialize = function () {
  69795. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69796. serializationObject.customType = "DefaultRenderingPipeline";
  69797. return serializationObject;
  69798. };
  69799. /**
  69800. * Parse the serialized pipeline
  69801. * @param source Source pipeline.
  69802. * @param scene The scene to load the pipeline to.
  69803. * @param rootUrl The URL of the serialized pipeline.
  69804. * @returns An instantiated pipeline from the serialized object.
  69805. */
  69806. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69807. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  69808. };
  69809. __decorate([
  69810. BABYLON.serialize()
  69811. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  69812. __decorate([
  69813. BABYLON.serialize()
  69814. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  69815. __decorate([
  69816. BABYLON.serialize()
  69817. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  69818. __decorate([
  69819. BABYLON.serialize()
  69820. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  69821. __decorate([
  69822. BABYLON.serialize()
  69823. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  69824. __decorate([
  69825. BABYLON.serialize()
  69826. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  69827. __decorate([
  69828. BABYLON.serialize()
  69829. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  69830. __decorate([
  69831. BABYLON.serialize()
  69832. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  69833. __decorate([
  69834. BABYLON.serialize()
  69835. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  69836. __decorate([
  69837. BABYLON.serialize()
  69838. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  69839. __decorate([
  69840. BABYLON.serialize()
  69841. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  69842. __decorate([
  69843. BABYLON.serialize()
  69844. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  69845. __decorate([
  69846. BABYLON.serialize()
  69847. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  69848. return DefaultRenderingPipeline;
  69849. }(BABYLON.PostProcessRenderPipeline));
  69850. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  69851. })(BABYLON || (BABYLON = {}));
  69852. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  69853. var BABYLON;
  69854. (function (BABYLON) {
  69855. /**
  69856. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  69857. */
  69858. var GeometryBufferRenderer = /** @class */ (function () {
  69859. /**
  69860. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  69861. * @param scene The scene the buffer belongs to
  69862. * @param ratio How big is the buffer related to the main canvas.
  69863. */
  69864. function GeometryBufferRenderer(scene, ratio) {
  69865. if (ratio === void 0) { ratio = 1; }
  69866. this._enablePosition = false;
  69867. this._scene = scene;
  69868. this._ratio = ratio;
  69869. // Render target
  69870. this._createRenderTargets();
  69871. }
  69872. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  69873. /**
  69874. * Set the render list (meshes to be rendered) used in the G buffer.
  69875. */
  69876. set: function (meshes) {
  69877. this._multiRenderTarget.renderList = meshes;
  69878. },
  69879. enumerable: true,
  69880. configurable: true
  69881. });
  69882. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  69883. /**
  69884. * Gets wether or not G buffer are supported by the running hardware.
  69885. * This requires draw buffer supports
  69886. */
  69887. get: function () {
  69888. return this._multiRenderTarget.isSupported;
  69889. },
  69890. enumerable: true,
  69891. configurable: true
  69892. });
  69893. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  69894. /**
  69895. * Gets wether or not position are enabled for the G buffer.
  69896. */
  69897. get: function () {
  69898. return this._enablePosition;
  69899. },
  69900. /**
  69901. * Sets wether or not position are enabled for the G buffer.
  69902. */
  69903. set: function (enable) {
  69904. this._enablePosition = enable;
  69905. this.dispose();
  69906. this._createRenderTargets();
  69907. },
  69908. enumerable: true,
  69909. configurable: true
  69910. });
  69911. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  69912. /**
  69913. * Gets the scene associated with the buffer.
  69914. */
  69915. get: function () {
  69916. return this._scene;
  69917. },
  69918. enumerable: true,
  69919. configurable: true
  69920. });
  69921. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  69922. /**
  69923. * Gets the ratio used by the buffer during its creation.
  69924. * How big is the buffer related to the main canvas.
  69925. */
  69926. get: function () {
  69927. return this._ratio;
  69928. },
  69929. enumerable: true,
  69930. configurable: true
  69931. });
  69932. /**
  69933. * Checks wether everything is ready to render a submesh to the G buffer.
  69934. * @param subMesh the submesh to check readiness for
  69935. * @param useInstances is the mesh drawn using instance or not
  69936. * @returns true if ready otherwise false
  69937. */
  69938. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  69939. var material = subMesh.getMaterial();
  69940. if (material && material.disableDepthWrite) {
  69941. return false;
  69942. }
  69943. var defines = [];
  69944. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  69945. var mesh = subMesh.getMesh();
  69946. // Alpha test
  69947. if (material && material.needAlphaTesting()) {
  69948. defines.push("#define ALPHATEST");
  69949. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69950. attribs.push(BABYLON.VertexBuffer.UVKind);
  69951. defines.push("#define UV1");
  69952. }
  69953. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69954. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69955. defines.push("#define UV2");
  69956. }
  69957. }
  69958. // Buffers
  69959. if (this._enablePosition) {
  69960. defines.push("#define POSITION");
  69961. }
  69962. // Bones
  69963. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69964. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69965. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69966. if (mesh.numBoneInfluencers > 4) {
  69967. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69968. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69969. }
  69970. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69971. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  69972. }
  69973. else {
  69974. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69975. }
  69976. // Instances
  69977. if (useInstances) {
  69978. defines.push("#define INSTANCES");
  69979. attribs.push("world0");
  69980. attribs.push("world1");
  69981. attribs.push("world2");
  69982. attribs.push("world3");
  69983. }
  69984. // Get correct effect
  69985. var join = defines.join("\n");
  69986. if (this._cachedDefines !== join) {
  69987. this._cachedDefines = join;
  69988. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  69989. }
  69990. return this._effect.isReady();
  69991. };
  69992. /**
  69993. * Gets the current underlying G Buffer.
  69994. * @returns the buffer
  69995. */
  69996. GeometryBufferRenderer.prototype.getGBuffer = function () {
  69997. return this._multiRenderTarget;
  69998. };
  69999. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  70000. /**
  70001. * Gets the number of samples used to render the buffer (anti aliasing).
  70002. */
  70003. get: function () {
  70004. return this._multiRenderTarget.samples;
  70005. },
  70006. /**
  70007. * Sets the number of samples used to render the buffer (anti aliasing).
  70008. */
  70009. set: function (value) {
  70010. this._multiRenderTarget.samples = value;
  70011. },
  70012. enumerable: true,
  70013. configurable: true
  70014. });
  70015. /**
  70016. * Disposes the renderer and frees up associated resources.
  70017. */
  70018. GeometryBufferRenderer.prototype.dispose = function () {
  70019. this.getGBuffer().dispose();
  70020. };
  70021. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  70022. var _this = this;
  70023. var engine = this._scene.getEngine();
  70024. var count = this._enablePosition ? 3 : 2;
  70025. 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 });
  70026. if (!this.isSupported) {
  70027. return;
  70028. }
  70029. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70030. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70031. this._multiRenderTarget.refreshRate = 1;
  70032. this._multiRenderTarget.renderParticles = false;
  70033. this._multiRenderTarget.renderList = null;
  70034. // set default depth value to 1.0 (far away)
  70035. this._multiRenderTarget.onClearObservable.add(function (engine) {
  70036. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  70037. });
  70038. // Custom render function
  70039. var renderSubMesh = function (subMesh) {
  70040. var mesh = subMesh.getRenderingMesh();
  70041. var scene = _this._scene;
  70042. var engine = scene.getEngine();
  70043. var material = subMesh.getMaterial();
  70044. if (!material) {
  70045. return;
  70046. }
  70047. // Culling
  70048. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  70049. // Managing instances
  70050. var batch = mesh._getInstancesRenderList(subMesh._id);
  70051. if (batch.mustReturn) {
  70052. return;
  70053. }
  70054. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70055. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  70056. engine.enableEffect(_this._effect);
  70057. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  70058. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  70059. _this._effect.setMatrix("view", scene.getViewMatrix());
  70060. // Alpha test
  70061. if (material && material.needAlphaTesting()) {
  70062. var alphaTexture = material.getAlphaTestTexture();
  70063. if (alphaTexture) {
  70064. _this._effect.setTexture("diffuseSampler", alphaTexture);
  70065. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70066. }
  70067. }
  70068. // Bones
  70069. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70070. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70071. }
  70072. // Draw
  70073. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70074. }
  70075. };
  70076. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70077. var index;
  70078. if (depthOnlySubMeshes.length) {
  70079. engine.setColorWrite(false);
  70080. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70081. renderSubMesh(depthOnlySubMeshes.data[index]);
  70082. }
  70083. engine.setColorWrite(true);
  70084. }
  70085. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70086. renderSubMesh(opaqueSubMeshes.data[index]);
  70087. }
  70088. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70089. renderSubMesh(alphaTestSubMeshes.data[index]);
  70090. }
  70091. };
  70092. };
  70093. return GeometryBufferRenderer;
  70094. }());
  70095. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  70096. })(BABYLON || (BABYLON = {}));
  70097. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  70098. var BABYLON;
  70099. (function (BABYLON) {
  70100. var RefractionPostProcess = /** @class */ (function (_super) {
  70101. __extends(RefractionPostProcess, _super);
  70102. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  70103. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  70104. _this.color = color;
  70105. _this.depth = depth;
  70106. _this.colorLevel = colorLevel;
  70107. _this._ownRefractionTexture = true;
  70108. _this.onActivateObservable.add(function (cam) {
  70109. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  70110. });
  70111. _this.onApplyObservable.add(function (effect) {
  70112. effect.setColor3("baseColor", _this.color);
  70113. effect.setFloat("depth", _this.depth);
  70114. effect.setFloat("colorLevel", _this.colorLevel);
  70115. effect.setTexture("refractionSampler", _this._refTexture);
  70116. });
  70117. return _this;
  70118. }
  70119. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  70120. /**
  70121. * Gets or sets the refraction texture
  70122. * Please note that you are responsible for disposing the texture if you set it manually
  70123. */
  70124. get: function () {
  70125. return this._refTexture;
  70126. },
  70127. set: function (value) {
  70128. if (this._refTexture && this._ownRefractionTexture) {
  70129. this._refTexture.dispose();
  70130. }
  70131. this._refTexture = value;
  70132. this._ownRefractionTexture = false;
  70133. },
  70134. enumerable: true,
  70135. configurable: true
  70136. });
  70137. // Methods
  70138. RefractionPostProcess.prototype.dispose = function (camera) {
  70139. if (this._refTexture && this._ownRefractionTexture) {
  70140. this._refTexture.dispose();
  70141. this._refTexture = null;
  70142. }
  70143. _super.prototype.dispose.call(this, camera);
  70144. };
  70145. return RefractionPostProcess;
  70146. }(BABYLON.PostProcess));
  70147. BABYLON.RefractionPostProcess = RefractionPostProcess;
  70148. })(BABYLON || (BABYLON = {}));
  70149. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  70150. var BABYLON;
  70151. (function (BABYLON) {
  70152. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  70153. __extends(BlackAndWhitePostProcess, _super);
  70154. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  70155. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  70156. _this.degree = 1;
  70157. _this.onApplyObservable.add(function (effect) {
  70158. effect.setFloat("degree", _this.degree);
  70159. });
  70160. return _this;
  70161. }
  70162. return BlackAndWhitePostProcess;
  70163. }(BABYLON.PostProcess));
  70164. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  70165. })(BABYLON || (BABYLON = {}));
  70166. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  70167. var BABYLON;
  70168. (function (BABYLON) {
  70169. /**
  70170. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  70171. * input texture to perform effects such as edge detection or sharpening
  70172. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70173. */
  70174. var ConvolutionPostProcess = /** @class */ (function (_super) {
  70175. __extends(ConvolutionPostProcess, _super);
  70176. /**
  70177. * Creates a new instance of @see ConvolutionPostProcess
  70178. * @param name The name of the effect.
  70179. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  70180. * @param options The required width/height ratio to downsize to before computing the render pass.
  70181. * @param camera The camera to apply the render pass to.
  70182. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70183. * @param engine The engine which the post process will be applied. (default: current engine)
  70184. * @param reusable If the post process can be reused on the same frame. (default: false)
  70185. * @param textureType Type of textures used when performing the post process. (default: 0)
  70186. */
  70187. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  70188. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70189. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70190. _this.kernel = kernel;
  70191. _this.onApply = function (effect) {
  70192. effect.setFloat2("screenSize", _this.width, _this.height);
  70193. effect.setArray("kernel", _this.kernel);
  70194. };
  70195. return _this;
  70196. }
  70197. // Statics
  70198. /**
  70199. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70200. */
  70201. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  70202. /**
  70203. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70204. */
  70205. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  70206. /**
  70207. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70208. */
  70209. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  70210. /**
  70211. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70212. */
  70213. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  70214. /**
  70215. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70216. */
  70217. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  70218. /**
  70219. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70220. */
  70221. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  70222. return ConvolutionPostProcess;
  70223. }(BABYLON.PostProcess));
  70224. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  70225. })(BABYLON || (BABYLON = {}));
  70226. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  70227. var BABYLON;
  70228. (function (BABYLON) {
  70229. var FilterPostProcess = /** @class */ (function (_super) {
  70230. __extends(FilterPostProcess, _super);
  70231. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  70232. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  70233. _this.kernelMatrix = kernelMatrix;
  70234. _this.onApply = function (effect) {
  70235. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  70236. };
  70237. return _this;
  70238. }
  70239. return FilterPostProcess;
  70240. }(BABYLON.PostProcess));
  70241. BABYLON.FilterPostProcess = FilterPostProcess;
  70242. })(BABYLON || (BABYLON = {}));
  70243. //# sourceMappingURL=babylon.filterPostProcess.js.map
  70244. var BABYLON;
  70245. (function (BABYLON) {
  70246. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  70247. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  70248. __extends(VolumetricLightScatteringPostProcess, _super);
  70249. /**
  70250. * @constructor
  70251. * @param {string} name - The post-process name
  70252. * @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)
  70253. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  70254. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  70255. * @param {number} samples - The post-process quality, default 100
  70256. * @param {number} samplingMode - The post-process filtering mode
  70257. * @param {BABYLON.Engine} engine - The babylon engine
  70258. * @param {boolean} reusable - If the post-process is reusable
  70259. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  70260. */
  70261. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  70262. if (samples === void 0) { samples = 100; }
  70263. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70264. 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;
  70265. _this._screenCoordinates = BABYLON.Vector2.Zero();
  70266. /**
  70267. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  70268. * @type {Vector3}
  70269. */
  70270. _this.customMeshPosition = BABYLON.Vector3.Zero();
  70271. /**
  70272. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  70273. * @type {boolean}
  70274. */
  70275. _this.useCustomMeshPosition = false;
  70276. /**
  70277. * If the post-process should inverse the light scattering direction
  70278. * @type {boolean}
  70279. */
  70280. _this.invert = true;
  70281. /**
  70282. * Array containing the excluded meshes not rendered in the internal pass
  70283. */
  70284. _this.excludedMeshes = new Array();
  70285. /**
  70286. * Controls the overall intensity of the post-process
  70287. * @type {number}
  70288. */
  70289. _this.exposure = 0.3;
  70290. /**
  70291. * Dissipates each sample's contribution in range [0, 1]
  70292. * @type {number}
  70293. */
  70294. _this.decay = 0.96815;
  70295. /**
  70296. * Controls the overall intensity of each sample
  70297. * @type {number}
  70298. */
  70299. _this.weight = 0.58767;
  70300. /**
  70301. * Controls the density of each sample
  70302. * @type {number}
  70303. */
  70304. _this.density = 0.926;
  70305. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  70306. engine = scene.getEngine();
  70307. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  70308. // Configure mesh
  70309. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  70310. // Configure
  70311. _this._createPass(scene, ratio.passRatio || ratio);
  70312. _this.onActivate = function (camera) {
  70313. if (!_this.isSupported) {
  70314. _this.dispose(camera);
  70315. }
  70316. _this.onActivate = null;
  70317. };
  70318. _this.onApplyObservable.add(function (effect) {
  70319. _this._updateMeshScreenCoordinates(scene);
  70320. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  70321. effect.setFloat("exposure", _this.exposure);
  70322. effect.setFloat("decay", _this.decay);
  70323. effect.setFloat("weight", _this.weight);
  70324. effect.setFloat("density", _this.density);
  70325. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  70326. });
  70327. return _this;
  70328. }
  70329. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  70330. get: function () {
  70331. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70332. return false;
  70333. },
  70334. set: function (useDiffuseColor) {
  70335. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70336. },
  70337. enumerable: true,
  70338. configurable: true
  70339. });
  70340. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  70341. return "VolumetricLightScatteringPostProcess";
  70342. };
  70343. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  70344. var mesh = subMesh.getMesh();
  70345. // Render this.mesh as default
  70346. if (mesh === this.mesh && mesh.material) {
  70347. return mesh.material.isReady(mesh);
  70348. }
  70349. var defines = [];
  70350. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70351. var material = subMesh.getMaterial();
  70352. // Alpha test
  70353. if (material) {
  70354. if (material.needAlphaTesting()) {
  70355. defines.push("#define ALPHATEST");
  70356. }
  70357. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70358. attribs.push(BABYLON.VertexBuffer.UVKind);
  70359. defines.push("#define UV1");
  70360. }
  70361. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70362. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70363. defines.push("#define UV2");
  70364. }
  70365. }
  70366. // Bones
  70367. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70368. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70369. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70370. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70371. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  70372. }
  70373. else {
  70374. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70375. }
  70376. // Instances
  70377. if (useInstances) {
  70378. defines.push("#define INSTANCES");
  70379. attribs.push("world0");
  70380. attribs.push("world1");
  70381. attribs.push("world2");
  70382. attribs.push("world3");
  70383. }
  70384. // Get correct effect
  70385. var join = defines.join("\n");
  70386. if (this._cachedDefines !== join) {
  70387. this._cachedDefines = join;
  70388. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  70389. }
  70390. return this._volumetricLightScatteringPass.isReady();
  70391. };
  70392. /**
  70393. * Sets the new light position for light scattering effect
  70394. * @param {BABYLON.Vector3} The new custom light position
  70395. */
  70396. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  70397. this.customMeshPosition = position;
  70398. };
  70399. /**
  70400. * Returns the light position for light scattering effect
  70401. * @return {BABYLON.Vector3} The custom light position
  70402. */
  70403. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  70404. return this.customMeshPosition;
  70405. };
  70406. /**
  70407. * Disposes the internal assets and detaches the post-process from the camera
  70408. */
  70409. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  70410. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  70411. if (rttIndex !== -1) {
  70412. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  70413. }
  70414. this._volumetricLightScatteringRTT.dispose();
  70415. _super.prototype.dispose.call(this, camera);
  70416. };
  70417. /**
  70418. * Returns the render target texture used by the post-process
  70419. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  70420. */
  70421. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  70422. return this._volumetricLightScatteringRTT;
  70423. };
  70424. // Private methods
  70425. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  70426. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  70427. return true;
  70428. }
  70429. return false;
  70430. };
  70431. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  70432. var _this = this;
  70433. var engine = scene.getEngine();
  70434. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70435. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70436. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70437. this._volumetricLightScatteringRTT.renderList = null;
  70438. this._volumetricLightScatteringRTT.renderParticles = false;
  70439. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  70440. var camera = this.getCamera();
  70441. if (camera) {
  70442. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70443. }
  70444. else {
  70445. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70446. }
  70447. // Custom render function for submeshes
  70448. var renderSubMesh = function (subMesh) {
  70449. var mesh = subMesh.getRenderingMesh();
  70450. if (_this._meshExcluded(mesh)) {
  70451. return;
  70452. }
  70453. var material = subMesh.getMaterial();
  70454. if (!material) {
  70455. return;
  70456. }
  70457. var scene = mesh.getScene();
  70458. var engine = scene.getEngine();
  70459. // Culling
  70460. engine.setState(material.backFaceCulling);
  70461. // Managing instances
  70462. var batch = mesh._getInstancesRenderList(subMesh._id);
  70463. if (batch.mustReturn) {
  70464. return;
  70465. }
  70466. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70467. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  70468. var effect = _this._volumetricLightScatteringPass;
  70469. if (mesh === _this.mesh) {
  70470. if (subMesh.effect) {
  70471. effect = subMesh.effect;
  70472. }
  70473. else {
  70474. effect = material.getEffect();
  70475. }
  70476. }
  70477. engine.enableEffect(effect);
  70478. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  70479. if (mesh === _this.mesh) {
  70480. material.bind(mesh.getWorldMatrix(), mesh);
  70481. }
  70482. else {
  70483. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  70484. // Alpha test
  70485. if (material && material.needAlphaTesting()) {
  70486. var alphaTexture = material.getAlphaTestTexture();
  70487. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  70488. if (alphaTexture) {
  70489. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70490. }
  70491. }
  70492. // Bones
  70493. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70494. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70495. }
  70496. }
  70497. // Draw
  70498. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  70499. }
  70500. };
  70501. // Render target texture callbacks
  70502. var savedSceneClearColor;
  70503. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  70504. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  70505. savedSceneClearColor = scene.clearColor;
  70506. scene.clearColor = sceneClearColor;
  70507. });
  70508. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  70509. scene.clearColor = savedSceneClearColor;
  70510. });
  70511. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70512. var engine = scene.getEngine();
  70513. var index;
  70514. if (depthOnlySubMeshes.length) {
  70515. engine.setColorWrite(false);
  70516. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70517. renderSubMesh(depthOnlySubMeshes.data[index]);
  70518. }
  70519. engine.setColorWrite(true);
  70520. }
  70521. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70522. renderSubMesh(opaqueSubMeshes.data[index]);
  70523. }
  70524. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70525. renderSubMesh(alphaTestSubMeshes.data[index]);
  70526. }
  70527. if (transparentSubMeshes.length) {
  70528. // Sort sub meshes
  70529. for (index = 0; index < transparentSubMeshes.length; index++) {
  70530. var submesh = transparentSubMeshes.data[index];
  70531. var boundingInfo = submesh.getBoundingInfo();
  70532. if (boundingInfo && scene.activeCamera) {
  70533. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  70534. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  70535. }
  70536. }
  70537. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  70538. sortedArray.sort(function (a, b) {
  70539. // Alpha index first
  70540. if (a._alphaIndex > b._alphaIndex) {
  70541. return 1;
  70542. }
  70543. if (a._alphaIndex < b._alphaIndex) {
  70544. return -1;
  70545. }
  70546. // Then distance to camera
  70547. if (a._distanceToCamera < b._distanceToCamera) {
  70548. return 1;
  70549. }
  70550. if (a._distanceToCamera > b._distanceToCamera) {
  70551. return -1;
  70552. }
  70553. return 0;
  70554. });
  70555. // Render sub meshes
  70556. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  70557. for (index = 0; index < sortedArray.length; index++) {
  70558. renderSubMesh(sortedArray[index]);
  70559. }
  70560. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70561. }
  70562. };
  70563. };
  70564. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  70565. var transform = scene.getTransformMatrix();
  70566. var meshPosition;
  70567. if (this.useCustomMeshPosition) {
  70568. meshPosition = this.customMeshPosition;
  70569. }
  70570. else if (this.attachedNode) {
  70571. meshPosition = this.attachedNode.position;
  70572. }
  70573. else {
  70574. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  70575. }
  70576. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  70577. this._screenCoordinates.x = pos.x / this._viewPort.width;
  70578. this._screenCoordinates.y = pos.y / this._viewPort.height;
  70579. if (this.invert)
  70580. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  70581. };
  70582. // Static methods
  70583. /**
  70584. * Creates a default mesh for the Volumeric Light Scattering post-process
  70585. * @param {string} The mesh name
  70586. * @param {BABYLON.Scene} The scene where to create the mesh
  70587. * @return {BABYLON.Mesh} the default mesh
  70588. */
  70589. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  70590. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  70591. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  70592. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  70593. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  70594. mesh.material = material;
  70595. return mesh;
  70596. };
  70597. __decorate([
  70598. BABYLON.serializeAsVector3()
  70599. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  70600. __decorate([
  70601. BABYLON.serialize()
  70602. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  70603. __decorate([
  70604. BABYLON.serialize()
  70605. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  70606. __decorate([
  70607. BABYLON.serializeAsMeshReference()
  70608. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  70609. __decorate([
  70610. BABYLON.serialize()
  70611. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  70612. __decorate([
  70613. BABYLON.serialize()
  70614. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  70615. __decorate([
  70616. BABYLON.serialize()
  70617. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  70618. __decorate([
  70619. BABYLON.serialize()
  70620. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  70621. __decorate([
  70622. BABYLON.serialize()
  70623. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  70624. return VolumetricLightScatteringPostProcess;
  70625. }(BABYLON.PostProcess));
  70626. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  70627. })(BABYLON || (BABYLON = {}));
  70628. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  70629. //
  70630. // This post-process allows the modification of rendered colors by using
  70631. // a 'look-up table' (LUT). This effect is also called Color Grading.
  70632. //
  70633. // The object needs to be provided an url to a texture containing the color
  70634. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  70635. // Use an image editing software to tweak the LUT to match your needs.
  70636. //
  70637. // For an example of a color LUT, see here:
  70638. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  70639. // For explanations on color grading, see here:
  70640. // http://udn.epicgames.com/Three/ColorGrading.html
  70641. //
  70642. var BABYLON;
  70643. (function (BABYLON) {
  70644. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  70645. __extends(ColorCorrectionPostProcess, _super);
  70646. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  70647. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  70648. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70649. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  70650. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70651. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70652. _this.onApply = function (effect) {
  70653. effect.setTexture("colorTable", _this._colorTableTexture);
  70654. };
  70655. return _this;
  70656. }
  70657. return ColorCorrectionPostProcess;
  70658. }(BABYLON.PostProcess));
  70659. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  70660. })(BABYLON || (BABYLON = {}));
  70661. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  70662. var BABYLON;
  70663. (function (BABYLON) {
  70664. var TonemappingOperator;
  70665. (function (TonemappingOperator) {
  70666. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  70667. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  70668. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  70669. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  70670. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  70671. ;
  70672. var TonemapPostProcess = /** @class */ (function (_super) {
  70673. __extends(TonemapPostProcess, _super);
  70674. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  70675. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70676. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70677. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  70678. _this._operator = _operator;
  70679. _this.exposureAdjustment = exposureAdjustment;
  70680. var defines = "#define ";
  70681. if (_this._operator === TonemappingOperator.Hable)
  70682. defines += "HABLE_TONEMAPPING";
  70683. else if (_this._operator === TonemappingOperator.Reinhard)
  70684. defines += "REINHARD_TONEMAPPING";
  70685. else if (_this._operator === TonemappingOperator.HejiDawson)
  70686. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  70687. else if (_this._operator === TonemappingOperator.Photographic)
  70688. defines += "PHOTOGRAPHIC_TONEMAPPING";
  70689. //sadly a second call to create the effect.
  70690. _this.updateEffect(defines);
  70691. _this.onApply = function (effect) {
  70692. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  70693. };
  70694. return _this;
  70695. }
  70696. return TonemapPostProcess;
  70697. }(BABYLON.PostProcess));
  70698. BABYLON.TonemapPostProcess = TonemapPostProcess;
  70699. })(BABYLON || (BABYLON = {}));
  70700. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  70701. var BABYLON;
  70702. (function (BABYLON) {
  70703. var DisplayPassPostProcess = /** @class */ (function (_super) {
  70704. __extends(DisplayPassPostProcess, _super);
  70705. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  70706. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  70707. }
  70708. return DisplayPassPostProcess;
  70709. }(BABYLON.PostProcess));
  70710. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  70711. })(BABYLON || (BABYLON = {}));
  70712. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  70713. var BABYLON;
  70714. (function (BABYLON) {
  70715. var HighlightsPostProcess = /** @class */ (function (_super) {
  70716. __extends(HighlightsPostProcess, _super);
  70717. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70718. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70719. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70720. }
  70721. return HighlightsPostProcess;
  70722. }(BABYLON.PostProcess));
  70723. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  70724. })(BABYLON || (BABYLON = {}));
  70725. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  70726. var BABYLON;
  70727. (function (BABYLON) {
  70728. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  70729. __extends(ImageProcessingPostProcess, _super);
  70730. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  70731. if (camera === void 0) { camera = null; }
  70732. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70733. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  70734. _this._fromLinearSpace = true;
  70735. /**
  70736. * Defines cache preventing GC.
  70737. */
  70738. _this._defines = {
  70739. IMAGEPROCESSING: false,
  70740. VIGNETTE: false,
  70741. VIGNETTEBLENDMODEMULTIPLY: false,
  70742. VIGNETTEBLENDMODEOPAQUE: false,
  70743. TONEMAPPING: false,
  70744. CONTRAST: false,
  70745. COLORCURVES: false,
  70746. COLORGRADING: false,
  70747. COLORGRADING3D: false,
  70748. FROMLINEARSPACE: false,
  70749. SAMPLER3DGREENDEPTH: false,
  70750. SAMPLER3DBGRMAP: false,
  70751. IMAGEPROCESSINGPOSTPROCESS: false,
  70752. EXPOSURE: false,
  70753. GRAIN: false,
  70754. };
  70755. // Setup the configuration as forced by the constructor. This would then not force the
  70756. // scene materials output in linear space and let untouched the default forward pass.
  70757. if (imageProcessingConfiguration) {
  70758. imageProcessingConfiguration.applyByPostProcess = true;
  70759. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  70760. // This will cause the shader to be compiled
  70761. _this.fromLinearSpace = false;
  70762. }
  70763. else {
  70764. _this._attachImageProcessingConfiguration(null, true);
  70765. _this.imageProcessingConfiguration.applyByPostProcess = true;
  70766. }
  70767. _this.onApply = function (effect) {
  70768. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  70769. };
  70770. return _this;
  70771. }
  70772. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  70773. /**
  70774. * Gets the image processing configuration used either in this material.
  70775. */
  70776. get: function () {
  70777. return this._imageProcessingConfiguration;
  70778. },
  70779. /**
  70780. * Sets the Default image processing configuration used either in the this material.
  70781. *
  70782. * If sets to null, the scene one is in use.
  70783. */
  70784. set: function (value) {
  70785. this._attachImageProcessingConfiguration(value);
  70786. },
  70787. enumerable: true,
  70788. configurable: true
  70789. });
  70790. /**
  70791. * Attaches a new image processing configuration to the PBR Material.
  70792. * @param configuration
  70793. */
  70794. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  70795. var _this = this;
  70796. if (doNotBuild === void 0) { doNotBuild = false; }
  70797. if (configuration === this._imageProcessingConfiguration) {
  70798. return;
  70799. }
  70800. // Detaches observer.
  70801. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70802. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70803. }
  70804. // Pick the scene configuration if needed.
  70805. if (!configuration) {
  70806. var scene = null;
  70807. var engine = this.getEngine();
  70808. var camera = this.getCamera();
  70809. if (camera) {
  70810. scene = camera.getScene();
  70811. }
  70812. else if (engine && engine.scenes) {
  70813. var scenes = engine.scenes;
  70814. scene = scenes[scenes.length - 1];
  70815. }
  70816. else {
  70817. scene = BABYLON.Engine.LastCreatedScene;
  70818. }
  70819. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  70820. }
  70821. else {
  70822. this._imageProcessingConfiguration = configuration;
  70823. }
  70824. // Attaches observer.
  70825. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  70826. _this._updateParameters();
  70827. });
  70828. // Ensure the effect will be rebuilt.
  70829. if (!doNotBuild) {
  70830. this._updateParameters();
  70831. }
  70832. };
  70833. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  70834. /**
  70835. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70836. */
  70837. get: function () {
  70838. return this.imageProcessingConfiguration.colorCurves;
  70839. },
  70840. /**
  70841. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70842. */
  70843. set: function (value) {
  70844. this.imageProcessingConfiguration.colorCurves = value;
  70845. },
  70846. enumerable: true,
  70847. configurable: true
  70848. });
  70849. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  70850. /**
  70851. * Gets wether the color curves effect is enabled.
  70852. */
  70853. get: function () {
  70854. return this.imageProcessingConfiguration.colorCurvesEnabled;
  70855. },
  70856. /**
  70857. * Sets wether the color curves effect is enabled.
  70858. */
  70859. set: function (value) {
  70860. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  70861. },
  70862. enumerable: true,
  70863. configurable: true
  70864. });
  70865. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  70866. /**
  70867. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70868. */
  70869. get: function () {
  70870. return this.imageProcessingConfiguration.colorGradingTexture;
  70871. },
  70872. /**
  70873. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70874. */
  70875. set: function (value) {
  70876. this.imageProcessingConfiguration.colorGradingTexture = value;
  70877. },
  70878. enumerable: true,
  70879. configurable: true
  70880. });
  70881. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  70882. /**
  70883. * Gets wether the color grading effect is enabled.
  70884. */
  70885. get: function () {
  70886. return this.imageProcessingConfiguration.colorGradingEnabled;
  70887. },
  70888. /**
  70889. * Gets wether the color grading effect is enabled.
  70890. */
  70891. set: function (value) {
  70892. this.imageProcessingConfiguration.colorGradingEnabled = value;
  70893. },
  70894. enumerable: true,
  70895. configurable: true
  70896. });
  70897. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  70898. /**
  70899. * Gets exposure used in the effect.
  70900. */
  70901. get: function () {
  70902. return this.imageProcessingConfiguration.exposure;
  70903. },
  70904. /**
  70905. * Sets exposure used in the effect.
  70906. */
  70907. set: function (value) {
  70908. this.imageProcessingConfiguration.exposure = value;
  70909. },
  70910. enumerable: true,
  70911. configurable: true
  70912. });
  70913. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  70914. /**
  70915. * Gets wether tonemapping is enabled or not.
  70916. */
  70917. get: function () {
  70918. return this._imageProcessingConfiguration.toneMappingEnabled;
  70919. },
  70920. /**
  70921. * Sets wether tonemapping is enabled or not
  70922. */
  70923. set: function (value) {
  70924. this._imageProcessingConfiguration.toneMappingEnabled = value;
  70925. },
  70926. enumerable: true,
  70927. configurable: true
  70928. });
  70929. ;
  70930. ;
  70931. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  70932. /**
  70933. * Gets contrast used in the effect.
  70934. */
  70935. get: function () {
  70936. return this.imageProcessingConfiguration.contrast;
  70937. },
  70938. /**
  70939. * Sets contrast used in the effect.
  70940. */
  70941. set: function (value) {
  70942. this.imageProcessingConfiguration.contrast = value;
  70943. },
  70944. enumerable: true,
  70945. configurable: true
  70946. });
  70947. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  70948. /**
  70949. * Gets Vignette stretch size.
  70950. */
  70951. get: function () {
  70952. return this.imageProcessingConfiguration.vignetteStretch;
  70953. },
  70954. /**
  70955. * Sets Vignette stretch size.
  70956. */
  70957. set: function (value) {
  70958. this.imageProcessingConfiguration.vignetteStretch = value;
  70959. },
  70960. enumerable: true,
  70961. configurable: true
  70962. });
  70963. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  70964. /**
  70965. * Gets Vignette centre X Offset.
  70966. */
  70967. get: function () {
  70968. return this.imageProcessingConfiguration.vignetteCentreX;
  70969. },
  70970. /**
  70971. * Sets Vignette centre X Offset.
  70972. */
  70973. set: function (value) {
  70974. this.imageProcessingConfiguration.vignetteCentreX = value;
  70975. },
  70976. enumerable: true,
  70977. configurable: true
  70978. });
  70979. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  70980. /**
  70981. * Gets Vignette centre Y Offset.
  70982. */
  70983. get: function () {
  70984. return this.imageProcessingConfiguration.vignetteCentreY;
  70985. },
  70986. /**
  70987. * Sets Vignette centre Y Offset.
  70988. */
  70989. set: function (value) {
  70990. this.imageProcessingConfiguration.vignetteCentreY = value;
  70991. },
  70992. enumerable: true,
  70993. configurable: true
  70994. });
  70995. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  70996. /**
  70997. * Gets Vignette weight or intensity of the vignette effect.
  70998. */
  70999. get: function () {
  71000. return this.imageProcessingConfiguration.vignetteWeight;
  71001. },
  71002. /**
  71003. * Sets Vignette weight or intensity of the vignette effect.
  71004. */
  71005. set: function (value) {
  71006. this.imageProcessingConfiguration.vignetteWeight = value;
  71007. },
  71008. enumerable: true,
  71009. configurable: true
  71010. });
  71011. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  71012. /**
  71013. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71014. * if vignetteEnabled is set to true.
  71015. */
  71016. get: function () {
  71017. return this.imageProcessingConfiguration.vignetteColor;
  71018. },
  71019. /**
  71020. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71021. * if vignetteEnabled is set to true.
  71022. */
  71023. set: function (value) {
  71024. this.imageProcessingConfiguration.vignetteColor = value;
  71025. },
  71026. enumerable: true,
  71027. configurable: true
  71028. });
  71029. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  71030. /**
  71031. * Gets Camera field of view used by the Vignette effect.
  71032. */
  71033. get: function () {
  71034. return this.imageProcessingConfiguration.vignetteCameraFov;
  71035. },
  71036. /**
  71037. * Sets Camera field of view used by the Vignette effect.
  71038. */
  71039. set: function (value) {
  71040. this.imageProcessingConfiguration.vignetteCameraFov = value;
  71041. },
  71042. enumerable: true,
  71043. configurable: true
  71044. });
  71045. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  71046. /**
  71047. * Gets the vignette blend mode allowing different kind of effect.
  71048. */
  71049. get: function () {
  71050. return this.imageProcessingConfiguration.vignetteBlendMode;
  71051. },
  71052. /**
  71053. * Sets the vignette blend mode allowing different kind of effect.
  71054. */
  71055. set: function (value) {
  71056. this.imageProcessingConfiguration.vignetteBlendMode = value;
  71057. },
  71058. enumerable: true,
  71059. configurable: true
  71060. });
  71061. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  71062. /**
  71063. * Gets wether the vignette effect is enabled.
  71064. */
  71065. get: function () {
  71066. return this.imageProcessingConfiguration.vignetteEnabled;
  71067. },
  71068. /**
  71069. * Sets wether the vignette effect is enabled.
  71070. */
  71071. set: function (value) {
  71072. this.imageProcessingConfiguration.vignetteEnabled = value;
  71073. },
  71074. enumerable: true,
  71075. configurable: true
  71076. });
  71077. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  71078. /**
  71079. * Gets wether the grain effect is enabled.
  71080. */
  71081. get: function () {
  71082. return this.imageProcessingConfiguration.grainEnabled;
  71083. },
  71084. /**
  71085. * Sets wether the grain effect is enabled.
  71086. */
  71087. set: function (value) {
  71088. this.imageProcessingConfiguration.grainEnabled = value;
  71089. },
  71090. enumerable: true,
  71091. configurable: true
  71092. });
  71093. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  71094. /**
  71095. * Gets the grain effect's intensity.
  71096. */
  71097. get: function () {
  71098. return this.imageProcessingConfiguration.grainIntensity;
  71099. },
  71100. /**
  71101. * Sets the grain effect's intensity.
  71102. */
  71103. set: function (value) {
  71104. this.imageProcessingConfiguration.grainIntensity = value;
  71105. },
  71106. enumerable: true,
  71107. configurable: true
  71108. });
  71109. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  71110. /**
  71111. * Gets wether the grain effect is animated.
  71112. */
  71113. get: function () {
  71114. return this.imageProcessingConfiguration.grainAnimated;
  71115. },
  71116. /**
  71117. * Sets wether the grain effect is animated.
  71118. */
  71119. set: function (value) {
  71120. this.imageProcessingConfiguration.grainAnimated = value;
  71121. },
  71122. enumerable: true,
  71123. configurable: true
  71124. });
  71125. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  71126. /**
  71127. * Gets wether the input of the processing is in Gamma or Linear Space.
  71128. */
  71129. get: function () {
  71130. return this._fromLinearSpace;
  71131. },
  71132. /**
  71133. * Sets wether the input of the processing is in Gamma or Linear Space.
  71134. */
  71135. set: function (value) {
  71136. if (this._fromLinearSpace === value) {
  71137. return;
  71138. }
  71139. this._fromLinearSpace = value;
  71140. this._updateParameters();
  71141. },
  71142. enumerable: true,
  71143. configurable: true
  71144. });
  71145. ImageProcessingPostProcess.prototype.getClassName = function () {
  71146. return "ImageProcessingPostProcess";
  71147. };
  71148. ImageProcessingPostProcess.prototype._updateParameters = function () {
  71149. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  71150. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  71151. var defines = "";
  71152. for (var define in this._defines) {
  71153. if (this._defines[define]) {
  71154. defines += "#define " + define + ";\r\n";
  71155. }
  71156. }
  71157. var samplers = ["textureSampler"];
  71158. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  71159. var uniforms = ["scale"];
  71160. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  71161. this.updateEffect(defines, uniforms, samplers);
  71162. };
  71163. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  71164. _super.prototype.dispose.call(this, camera);
  71165. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71166. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71167. }
  71168. this.imageProcessingConfiguration.applyByPostProcess = false;
  71169. };
  71170. __decorate([
  71171. BABYLON.serialize()
  71172. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  71173. return ImageProcessingPostProcess;
  71174. }(BABYLON.PostProcess));
  71175. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  71176. })(BABYLON || (BABYLON = {}));
  71177. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  71178. var BABYLON;
  71179. (function (BABYLON) {
  71180. var Bone = /** @class */ (function (_super) {
  71181. __extends(Bone, _super);
  71182. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  71183. if (parentBone === void 0) { parentBone = null; }
  71184. if (localMatrix === void 0) { localMatrix = null; }
  71185. if (restPose === void 0) { restPose = null; }
  71186. if (baseMatrix === void 0) { baseMatrix = null; }
  71187. if (index === void 0) { index = null; }
  71188. var _this = _super.call(this, name, skeleton.getScene()) || this;
  71189. _this.name = name;
  71190. _this.children = new Array();
  71191. _this.animations = new Array();
  71192. // Set this value to map this bone to a different index in the transform matrices.
  71193. // Set this value to -1 to exclude the bone from the transform matrices.
  71194. _this._index = null;
  71195. _this._worldTransform = new BABYLON.Matrix();
  71196. _this._absoluteTransform = new BABYLON.Matrix();
  71197. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  71198. _this._scaleMatrix = BABYLON.Matrix.Identity();
  71199. _this._scaleVector = BABYLON.Vector3.One();
  71200. _this._negateScaleChildren = BABYLON.Vector3.One();
  71201. _this._scalingDeterminant = 1;
  71202. _this._skeleton = skeleton;
  71203. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  71204. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  71205. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  71206. _this._index = index;
  71207. skeleton.bones.push(_this);
  71208. _this.setParent(parentBone, false);
  71209. _this._updateDifferenceMatrix();
  71210. return _this;
  71211. }
  71212. Object.defineProperty(Bone.prototype, "_matrix", {
  71213. get: function () {
  71214. return this._localMatrix;
  71215. },
  71216. set: function (val) {
  71217. if (this._localMatrix) {
  71218. this._localMatrix.copyFrom(val);
  71219. }
  71220. else {
  71221. this._localMatrix = val;
  71222. }
  71223. },
  71224. enumerable: true,
  71225. configurable: true
  71226. });
  71227. // Members
  71228. Bone.prototype.getSkeleton = function () {
  71229. return this._skeleton;
  71230. };
  71231. Bone.prototype.getParent = function () {
  71232. return this._parent;
  71233. };
  71234. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  71235. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71236. if (this._parent === parent) {
  71237. return;
  71238. }
  71239. if (this._parent) {
  71240. var index = this._parent.children.indexOf(this);
  71241. if (index !== -1) {
  71242. this._parent.children.splice(index, 1);
  71243. }
  71244. }
  71245. this._parent = parent;
  71246. if (this._parent) {
  71247. this._parent.children.push(this);
  71248. }
  71249. if (updateDifferenceMatrix) {
  71250. this._updateDifferenceMatrix();
  71251. }
  71252. };
  71253. Bone.prototype.getLocalMatrix = function () {
  71254. return this._localMatrix;
  71255. };
  71256. Bone.prototype.getBaseMatrix = function () {
  71257. return this._baseMatrix;
  71258. };
  71259. Bone.prototype.getRestPose = function () {
  71260. return this._restPose;
  71261. };
  71262. Bone.prototype.returnToRest = function () {
  71263. this.updateMatrix(this._restPose.clone());
  71264. };
  71265. Bone.prototype.getWorldMatrix = function () {
  71266. return this._worldTransform;
  71267. };
  71268. Bone.prototype.getInvertedAbsoluteTransform = function () {
  71269. return this._invertedAbsoluteTransform;
  71270. };
  71271. Bone.prototype.getAbsoluteTransform = function () {
  71272. return this._absoluteTransform;
  71273. };
  71274. Object.defineProperty(Bone.prototype, "position", {
  71275. // Properties (matches AbstractMesh properties)
  71276. get: function () {
  71277. return this.getPosition();
  71278. },
  71279. set: function (newPosition) {
  71280. this.setPosition(newPosition);
  71281. },
  71282. enumerable: true,
  71283. configurable: true
  71284. });
  71285. Object.defineProperty(Bone.prototype, "rotation", {
  71286. get: function () {
  71287. return this.getRotation();
  71288. },
  71289. set: function (newRotation) {
  71290. this.setRotation(newRotation);
  71291. },
  71292. enumerable: true,
  71293. configurable: true
  71294. });
  71295. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  71296. get: function () {
  71297. return this.getRotationQuaternion();
  71298. },
  71299. set: function (newRotation) {
  71300. this.setRotationQuaternion(newRotation);
  71301. },
  71302. enumerable: true,
  71303. configurable: true
  71304. });
  71305. Object.defineProperty(Bone.prototype, "scaling", {
  71306. get: function () {
  71307. return this.getScale();
  71308. },
  71309. set: function (newScaling) {
  71310. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  71311. },
  71312. enumerable: true,
  71313. configurable: true
  71314. });
  71315. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  71316. /**
  71317. * Gets the animation properties override
  71318. */
  71319. get: function () {
  71320. return this._skeleton.animationPropertiesOverride;
  71321. },
  71322. enumerable: true,
  71323. configurable: true
  71324. });
  71325. // Methods
  71326. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  71327. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71328. this._baseMatrix = matrix.clone();
  71329. this._localMatrix = matrix.clone();
  71330. this._skeleton._markAsDirty();
  71331. if (updateDifferenceMatrix) {
  71332. this._updateDifferenceMatrix();
  71333. }
  71334. };
  71335. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  71336. if (!rootMatrix) {
  71337. rootMatrix = this._baseMatrix;
  71338. }
  71339. if (this._parent) {
  71340. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71341. }
  71342. else {
  71343. this._absoluteTransform.copyFrom(rootMatrix);
  71344. }
  71345. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  71346. for (var index = 0; index < this.children.length; index++) {
  71347. this.children[index]._updateDifferenceMatrix();
  71348. }
  71349. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  71350. };
  71351. Bone.prototype.markAsDirty = function () {
  71352. this._currentRenderId++;
  71353. this._skeleton._markAsDirty();
  71354. };
  71355. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  71356. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71357. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  71358. // all animation may be coming from a library skeleton, so may need to create animation
  71359. if (this.animations.length === 0) {
  71360. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  71361. this.animations[0].setKeys([]);
  71362. }
  71363. // get animation info / verify there is such a range from the source bone
  71364. var sourceRange = source.animations[0].getRange(rangeName);
  71365. if (!sourceRange) {
  71366. return false;
  71367. }
  71368. var from = sourceRange.from;
  71369. var to = sourceRange.to;
  71370. var sourceKeys = source.animations[0].getKeys();
  71371. // rescaling prep
  71372. var sourceBoneLength = source.length;
  71373. var sourceParent = source.getParent();
  71374. var parent = this.getParent();
  71375. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  71376. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  71377. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  71378. var destKeys = this.animations[0].getKeys();
  71379. // loop vars declaration
  71380. var orig;
  71381. var origTranslation;
  71382. var mat;
  71383. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  71384. orig = sourceKeys[key];
  71385. if (orig.frame >= from && orig.frame <= to) {
  71386. if (rescaleAsRequired) {
  71387. mat = orig.value.clone();
  71388. // scale based on parent ratio, when bone has parent
  71389. if (parentScalingReqd) {
  71390. origTranslation = mat.getTranslation();
  71391. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  71392. // scale based on skeleton dimension ratio when root bone, and value is passed
  71393. }
  71394. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  71395. origTranslation = mat.getTranslation();
  71396. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  71397. // use original when root bone, and no data for skelDimensionsRatio
  71398. }
  71399. else {
  71400. mat = orig.value;
  71401. }
  71402. }
  71403. else {
  71404. mat = orig.value;
  71405. }
  71406. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  71407. }
  71408. }
  71409. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  71410. return true;
  71411. };
  71412. /**
  71413. * Translate the bone in local or world space.
  71414. * @param vec The amount to translate the bone.
  71415. * @param space The space that the translation is in.
  71416. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71417. */
  71418. Bone.prototype.translate = function (vec, space, mesh) {
  71419. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71420. var lm = this.getLocalMatrix();
  71421. if (space == BABYLON.Space.LOCAL) {
  71422. lm.m[12] += vec.x;
  71423. lm.m[13] += vec.y;
  71424. lm.m[14] += vec.z;
  71425. }
  71426. else {
  71427. var wm = null;
  71428. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71429. if (mesh) {
  71430. wm = mesh.getWorldMatrix();
  71431. }
  71432. this._skeleton.computeAbsoluteTransforms();
  71433. var tmat = Bone._tmpMats[0];
  71434. var tvec = Bone._tmpVecs[0];
  71435. if (this._parent) {
  71436. if (mesh && wm) {
  71437. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71438. tmat.multiplyToRef(wm, tmat);
  71439. }
  71440. else {
  71441. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71442. }
  71443. }
  71444. tmat.m[12] = 0;
  71445. tmat.m[13] = 0;
  71446. tmat.m[14] = 0;
  71447. tmat.invert();
  71448. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  71449. lm.m[12] += tvec.x;
  71450. lm.m[13] += tvec.y;
  71451. lm.m[14] += tvec.z;
  71452. }
  71453. this.markAsDirty();
  71454. };
  71455. /**
  71456. * Set the postion of the bone in local or world space.
  71457. * @param position The position to set the bone.
  71458. * @param space The space that the position is in.
  71459. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71460. */
  71461. Bone.prototype.setPosition = function (position, space, mesh) {
  71462. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71463. var lm = this.getLocalMatrix();
  71464. if (space == BABYLON.Space.LOCAL) {
  71465. lm.m[12] = position.x;
  71466. lm.m[13] = position.y;
  71467. lm.m[14] = position.z;
  71468. }
  71469. else {
  71470. var wm = null;
  71471. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71472. if (mesh) {
  71473. wm = mesh.getWorldMatrix();
  71474. }
  71475. this._skeleton.computeAbsoluteTransforms();
  71476. var tmat = Bone._tmpMats[0];
  71477. var vec = Bone._tmpVecs[0];
  71478. if (this._parent) {
  71479. if (mesh && wm) {
  71480. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71481. tmat.multiplyToRef(wm, tmat);
  71482. }
  71483. else {
  71484. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71485. }
  71486. }
  71487. tmat.invert();
  71488. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  71489. lm.m[12] = vec.x;
  71490. lm.m[13] = vec.y;
  71491. lm.m[14] = vec.z;
  71492. }
  71493. this.markAsDirty();
  71494. };
  71495. /**
  71496. * Set the absolute postion of the bone (world space).
  71497. * @param position The position to set the bone.
  71498. * @param mesh The mesh that this bone is attached to.
  71499. */
  71500. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  71501. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  71502. };
  71503. /**
  71504. * Set the scale of the bone on the x, y and z axes.
  71505. * @param x The scale of the bone on the x axis.
  71506. * @param x The scale of the bone on the y axis.
  71507. * @param z The scale of the bone on the z axis.
  71508. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71509. */
  71510. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  71511. if (scaleChildren === void 0) { scaleChildren = false; }
  71512. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  71513. if (!scaleChildren) {
  71514. this._negateScaleChildren.x = 1 / x;
  71515. this._negateScaleChildren.y = 1 / y;
  71516. this._negateScaleChildren.z = 1 / z;
  71517. }
  71518. this._syncScaleVector();
  71519. }
  71520. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  71521. };
  71522. /**
  71523. * Scale the bone on the x, y and z axes.
  71524. * @param x The amount to scale the bone on the x axis.
  71525. * @param x The amount to scale the bone on the y axis.
  71526. * @param z The amount to scale the bone on the z axis.
  71527. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71528. */
  71529. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  71530. if (scaleChildren === void 0) { scaleChildren = false; }
  71531. var locMat = this.getLocalMatrix();
  71532. var origLocMat = Bone._tmpMats[0];
  71533. origLocMat.copyFrom(locMat);
  71534. var origLocMatInv = Bone._tmpMats[1];
  71535. origLocMatInv.copyFrom(origLocMat);
  71536. origLocMatInv.invert();
  71537. var scaleMat = Bone._tmpMats[2];
  71538. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  71539. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  71540. this._scaleVector.x *= x;
  71541. this._scaleVector.y *= y;
  71542. this._scaleVector.z *= z;
  71543. locMat.multiplyToRef(origLocMatInv, locMat);
  71544. locMat.multiplyToRef(scaleMat, locMat);
  71545. locMat.multiplyToRef(origLocMat, locMat);
  71546. var parent = this.getParent();
  71547. if (parent) {
  71548. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  71549. }
  71550. else {
  71551. this.getAbsoluteTransform().copyFrom(locMat);
  71552. }
  71553. var len = this.children.length;
  71554. scaleMat.invert();
  71555. for (var i = 0; i < len; i++) {
  71556. var child = this.children[i];
  71557. var cm = child.getLocalMatrix();
  71558. cm.multiplyToRef(scaleMat, cm);
  71559. var lm = child.getLocalMatrix();
  71560. lm.m[12] *= x;
  71561. lm.m[13] *= y;
  71562. lm.m[14] *= z;
  71563. }
  71564. this.computeAbsoluteTransforms();
  71565. if (scaleChildren) {
  71566. for (var i = 0; i < len; i++) {
  71567. this.children[i].scale(x, y, z, scaleChildren);
  71568. }
  71569. }
  71570. this.markAsDirty();
  71571. };
  71572. /**
  71573. * Set the yaw, pitch, and roll of the bone in local or world space.
  71574. * @param yaw The rotation of the bone on the y axis.
  71575. * @param pitch The rotation of the bone on the x axis.
  71576. * @param roll The rotation of the bone on the z axis.
  71577. * @param space The space that the axes of rotation are in.
  71578. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71579. */
  71580. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  71581. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71582. var rotMat = Bone._tmpMats[0];
  71583. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  71584. var rotMatInv = Bone._tmpMats[1];
  71585. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71586. rotMatInv.multiplyToRef(rotMat, rotMat);
  71587. this._rotateWithMatrix(rotMat, space, mesh);
  71588. };
  71589. /**
  71590. * Rotate the bone on an axis in local or world space.
  71591. * @param axis The axis to rotate the bone on.
  71592. * @param amount The amount to rotate the bone.
  71593. * @param space The space that the axis is in.
  71594. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71595. */
  71596. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  71597. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71598. var rmat = Bone._tmpMats[0];
  71599. rmat.m[12] = 0;
  71600. rmat.m[13] = 0;
  71601. rmat.m[14] = 0;
  71602. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  71603. this._rotateWithMatrix(rmat, space, mesh);
  71604. };
  71605. /**
  71606. * Set the rotation of the bone to a particular axis angle in local or world space.
  71607. * @param axis The axis to rotate the bone on.
  71608. * @param angle The angle that the bone should be rotated to.
  71609. * @param space The space that the axis is in.
  71610. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71611. */
  71612. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  71613. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71614. var rotMat = Bone._tmpMats[0];
  71615. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  71616. var rotMatInv = Bone._tmpMats[1];
  71617. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71618. rotMatInv.multiplyToRef(rotMat, rotMat);
  71619. this._rotateWithMatrix(rotMat, space, mesh);
  71620. };
  71621. /**
  71622. * Set the euler rotation of the bone in local of world space.
  71623. * @param rotation The euler rotation that the bone should be set to.
  71624. * @param space The space that the rotation is in.
  71625. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71626. */
  71627. Bone.prototype.setRotation = function (rotation, space, mesh) {
  71628. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71629. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  71630. };
  71631. /**
  71632. * Set the quaternion rotation of the bone in local of world space.
  71633. * @param quat The quaternion rotation that the bone should be set to.
  71634. * @param space The space that the rotation is in.
  71635. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71636. */
  71637. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  71638. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71639. var rotMatInv = Bone._tmpMats[0];
  71640. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71641. var rotMat = Bone._tmpMats[1];
  71642. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  71643. rotMatInv.multiplyToRef(rotMat, rotMat);
  71644. this._rotateWithMatrix(rotMat, space, mesh);
  71645. };
  71646. /**
  71647. * Set the rotation matrix of the bone in local of world space.
  71648. * @param rotMat The rotation matrix that the bone should be set to.
  71649. * @param space The space that the rotation is in.
  71650. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71651. */
  71652. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  71653. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71654. var rotMatInv = Bone._tmpMats[0];
  71655. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71656. var rotMat2 = Bone._tmpMats[1];
  71657. rotMat2.copyFrom(rotMat);
  71658. rotMatInv.multiplyToRef(rotMat, rotMat2);
  71659. this._rotateWithMatrix(rotMat2, space, mesh);
  71660. };
  71661. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  71662. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71663. var lmat = this.getLocalMatrix();
  71664. var lx = lmat.m[12];
  71665. var ly = lmat.m[13];
  71666. var lz = lmat.m[14];
  71667. var parent = this.getParent();
  71668. var parentScale = Bone._tmpMats[3];
  71669. var parentScaleInv = Bone._tmpMats[4];
  71670. if (parent) {
  71671. if (space == BABYLON.Space.WORLD) {
  71672. if (mesh) {
  71673. parentScale.copyFrom(mesh.getWorldMatrix());
  71674. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  71675. }
  71676. else {
  71677. parentScale.copyFrom(parent.getAbsoluteTransform());
  71678. }
  71679. }
  71680. else {
  71681. parentScale = parent._scaleMatrix;
  71682. }
  71683. parentScaleInv.copyFrom(parentScale);
  71684. parentScaleInv.invert();
  71685. lmat.multiplyToRef(parentScale, lmat);
  71686. lmat.multiplyToRef(rmat, lmat);
  71687. lmat.multiplyToRef(parentScaleInv, lmat);
  71688. }
  71689. else {
  71690. if (space == BABYLON.Space.WORLD && mesh) {
  71691. parentScale.copyFrom(mesh.getWorldMatrix());
  71692. parentScaleInv.copyFrom(parentScale);
  71693. parentScaleInv.invert();
  71694. lmat.multiplyToRef(parentScale, lmat);
  71695. lmat.multiplyToRef(rmat, lmat);
  71696. lmat.multiplyToRef(parentScaleInv, lmat);
  71697. }
  71698. else {
  71699. lmat.multiplyToRef(rmat, lmat);
  71700. }
  71701. }
  71702. lmat.m[12] = lx;
  71703. lmat.m[13] = ly;
  71704. lmat.m[14] = lz;
  71705. this.computeAbsoluteTransforms();
  71706. this.markAsDirty();
  71707. };
  71708. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  71709. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71710. if (space == BABYLON.Space.WORLD) {
  71711. var scaleMatrix = Bone._tmpMats[2];
  71712. scaleMatrix.copyFrom(this._scaleMatrix);
  71713. rotMatInv.copyFrom(this.getAbsoluteTransform());
  71714. if (mesh) {
  71715. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  71716. var meshScale = Bone._tmpMats[3];
  71717. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  71718. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  71719. }
  71720. rotMatInv.invert();
  71721. scaleMatrix.m[0] *= this._scalingDeterminant;
  71722. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71723. }
  71724. else {
  71725. rotMatInv.copyFrom(this.getLocalMatrix());
  71726. rotMatInv.invert();
  71727. var scaleMatrix = Bone._tmpMats[2];
  71728. scaleMatrix.copyFrom(this._scaleMatrix);
  71729. if (this._parent) {
  71730. var pscaleMatrix = Bone._tmpMats[3];
  71731. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  71732. pscaleMatrix.invert();
  71733. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  71734. }
  71735. else {
  71736. scaleMatrix.m[0] *= this._scalingDeterminant;
  71737. }
  71738. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71739. }
  71740. };
  71741. /**
  71742. * Get the scale of the bone
  71743. * @returns the scale of the bone
  71744. */
  71745. Bone.prototype.getScale = function () {
  71746. return this._scaleVector.clone();
  71747. };
  71748. /**
  71749. * Copy the scale of the bone to a vector3.
  71750. * @param result The vector3 to copy the scale to
  71751. */
  71752. Bone.prototype.getScaleToRef = function (result) {
  71753. result.copyFrom(this._scaleVector);
  71754. };
  71755. /**
  71756. * Get the position of the bone in local or world space.
  71757. * @param space The space that the returned position is in.
  71758. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71759. * @returns The position of the bone
  71760. */
  71761. Bone.prototype.getPosition = function (space, mesh) {
  71762. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71763. if (mesh === void 0) { mesh = null; }
  71764. var pos = BABYLON.Vector3.Zero();
  71765. this.getPositionToRef(space, mesh, pos);
  71766. return pos;
  71767. };
  71768. /**
  71769. * Copy the position of the bone to a vector3 in local or world space.
  71770. * @param space The space that the returned position is in.
  71771. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71772. * @param result The vector3 to copy the position to.
  71773. */
  71774. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  71775. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71776. if (space == BABYLON.Space.LOCAL) {
  71777. var lm = this.getLocalMatrix();
  71778. result.x = lm.m[12];
  71779. result.y = lm.m[13];
  71780. result.z = lm.m[14];
  71781. }
  71782. else {
  71783. var wm = null;
  71784. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71785. if (mesh) {
  71786. wm = mesh.getWorldMatrix();
  71787. }
  71788. this._skeleton.computeAbsoluteTransforms();
  71789. var tmat = Bone._tmpMats[0];
  71790. if (mesh && wm) {
  71791. tmat.copyFrom(this.getAbsoluteTransform());
  71792. tmat.multiplyToRef(wm, tmat);
  71793. }
  71794. else {
  71795. tmat = this.getAbsoluteTransform();
  71796. }
  71797. result.x = tmat.m[12];
  71798. result.y = tmat.m[13];
  71799. result.z = tmat.m[14];
  71800. }
  71801. };
  71802. /**
  71803. * Get the absolute position of the bone (world space).
  71804. * @param mesh The mesh that this bone is attached to.
  71805. * @returns The absolute position of the bone
  71806. */
  71807. Bone.prototype.getAbsolutePosition = function (mesh) {
  71808. if (mesh === void 0) { mesh = null; }
  71809. var pos = BABYLON.Vector3.Zero();
  71810. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  71811. return pos;
  71812. };
  71813. /**
  71814. * Copy the absolute position of the bone (world space) to the result param.
  71815. * @param mesh The mesh that this bone is attached to.
  71816. * @param result The vector3 to copy the absolute position to.
  71817. */
  71818. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  71819. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  71820. };
  71821. /**
  71822. * Compute the absolute transforms of this bone and its children.
  71823. */
  71824. Bone.prototype.computeAbsoluteTransforms = function () {
  71825. if (this._parent) {
  71826. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71827. }
  71828. else {
  71829. this._absoluteTransform.copyFrom(this._localMatrix);
  71830. var poseMatrix = this._skeleton.getPoseMatrix();
  71831. if (poseMatrix) {
  71832. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  71833. }
  71834. }
  71835. var children = this.children;
  71836. var len = children.length;
  71837. for (var i = 0; i < len; i++) {
  71838. children[i].computeAbsoluteTransforms();
  71839. }
  71840. };
  71841. Bone.prototype._syncScaleVector = function () {
  71842. var lm = this.getLocalMatrix();
  71843. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  71844. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  71845. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  71846. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  71847. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  71848. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  71849. this._scaleVector.x = xs * Math.sqrt(xsq);
  71850. this._scaleVector.y = ys * Math.sqrt(ysq);
  71851. this._scaleVector.z = zs * Math.sqrt(zsq);
  71852. if (this._parent) {
  71853. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  71854. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  71855. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  71856. }
  71857. 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);
  71858. };
  71859. /**
  71860. * Get the world direction from an axis that is in the local space of the bone.
  71861. * @param localAxis The local direction that is used to compute the world direction.
  71862. * @param mesh The mesh that this bone is attached to.
  71863. * @returns The world direction
  71864. */
  71865. Bone.prototype.getDirection = function (localAxis, mesh) {
  71866. if (mesh === void 0) { mesh = null; }
  71867. var result = BABYLON.Vector3.Zero();
  71868. this.getDirectionToRef(localAxis, mesh, result);
  71869. return result;
  71870. };
  71871. /**
  71872. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  71873. * @param localAxis The local direction that is used to compute the world direction.
  71874. * @param mesh The mesh that this bone is attached to.
  71875. * @param result The vector3 that the world direction will be copied to.
  71876. */
  71877. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  71878. if (mesh === void 0) { mesh = null; }
  71879. var wm = null;
  71880. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71881. if (mesh) {
  71882. wm = mesh.getWorldMatrix();
  71883. }
  71884. this._skeleton.computeAbsoluteTransforms();
  71885. var mat = Bone._tmpMats[0];
  71886. mat.copyFrom(this.getAbsoluteTransform());
  71887. if (mesh && wm) {
  71888. mat.multiplyToRef(wm, mat);
  71889. }
  71890. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  71891. result.normalize();
  71892. };
  71893. /**
  71894. * Get the euler rotation of the bone in local or world space.
  71895. * @param space The space that the rotation should be in.
  71896. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71897. * @returns The euler rotation
  71898. */
  71899. Bone.prototype.getRotation = function (space, mesh) {
  71900. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71901. if (mesh === void 0) { mesh = null; }
  71902. var result = BABYLON.Vector3.Zero();
  71903. this.getRotationToRef(space, mesh, result);
  71904. return result;
  71905. };
  71906. /**
  71907. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  71908. * @param space The space that the rotation should be in.
  71909. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71910. * @param result The vector3 that the rotation should be copied to.
  71911. */
  71912. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  71913. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71914. if (mesh === void 0) { mesh = null; }
  71915. var quat = Bone._tmpQuat;
  71916. this.getRotationQuaternionToRef(space, mesh, quat);
  71917. quat.toEulerAnglesToRef(result);
  71918. };
  71919. /**
  71920. * Get the quaternion rotation of the bone in either local or world space.
  71921. * @param space The space that the rotation should be in.
  71922. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71923. * @returns The quaternion rotation
  71924. */
  71925. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  71926. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71927. if (mesh === void 0) { mesh = null; }
  71928. var result = BABYLON.Quaternion.Identity();
  71929. this.getRotationQuaternionToRef(space, mesh, result);
  71930. return result;
  71931. };
  71932. /**
  71933. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  71934. * @param space The space that the rotation should be in.
  71935. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71936. * @param result The quaternion that the rotation should be copied to.
  71937. */
  71938. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  71939. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71940. if (mesh === void 0) { mesh = null; }
  71941. if (space == BABYLON.Space.LOCAL) {
  71942. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71943. }
  71944. else {
  71945. var mat = Bone._tmpMats[0];
  71946. var amat = this.getAbsoluteTransform();
  71947. if (mesh) {
  71948. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71949. }
  71950. else {
  71951. mat.copyFrom(amat);
  71952. }
  71953. mat.m[0] *= this._scalingDeterminant;
  71954. mat.m[1] *= this._scalingDeterminant;
  71955. mat.m[2] *= this._scalingDeterminant;
  71956. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71957. }
  71958. };
  71959. /**
  71960. * Get the rotation matrix of the bone in local or world space.
  71961. * @param space The space that the rotation should be in.
  71962. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71963. * @returns The rotation matrix
  71964. */
  71965. Bone.prototype.getRotationMatrix = function (space, mesh) {
  71966. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71967. var result = BABYLON.Matrix.Identity();
  71968. this.getRotationMatrixToRef(space, mesh, result);
  71969. return result;
  71970. };
  71971. /**
  71972. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  71973. * @param space The space that the rotation should be in.
  71974. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71975. * @param result The quaternion that the rotation should be copied to.
  71976. */
  71977. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  71978. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71979. if (space == BABYLON.Space.LOCAL) {
  71980. this.getLocalMatrix().getRotationMatrixToRef(result);
  71981. }
  71982. else {
  71983. var mat = Bone._tmpMats[0];
  71984. var amat = this.getAbsoluteTransform();
  71985. if (mesh) {
  71986. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71987. }
  71988. else {
  71989. mat.copyFrom(amat);
  71990. }
  71991. mat.m[0] *= this._scalingDeterminant;
  71992. mat.m[1] *= this._scalingDeterminant;
  71993. mat.m[2] *= this._scalingDeterminant;
  71994. mat.getRotationMatrixToRef(result);
  71995. }
  71996. };
  71997. /**
  71998. * Get the world position of a point that is in the local space of the bone.
  71999. * @param position The local position
  72000. * @param mesh The mesh that this bone is attached to.
  72001. * @returns The world position
  72002. */
  72003. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  72004. if (mesh === void 0) { mesh = null; }
  72005. var result = BABYLON.Vector3.Zero();
  72006. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  72007. return result;
  72008. };
  72009. /**
  72010. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  72011. * @param position The local position
  72012. * @param mesh The mesh that this bone is attached to.
  72013. * @param result The vector3 that the world position should be copied to.
  72014. */
  72015. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  72016. if (mesh === void 0) { mesh = null; }
  72017. var wm = null;
  72018. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72019. if (mesh) {
  72020. wm = mesh.getWorldMatrix();
  72021. }
  72022. this._skeleton.computeAbsoluteTransforms();
  72023. var tmat = Bone._tmpMats[0];
  72024. if (mesh && wm) {
  72025. tmat.copyFrom(this.getAbsoluteTransform());
  72026. tmat.multiplyToRef(wm, tmat);
  72027. }
  72028. else {
  72029. tmat = this.getAbsoluteTransform();
  72030. }
  72031. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72032. };
  72033. /**
  72034. * Get the local position of a point that is in world space.
  72035. * @param position The world position
  72036. * @param mesh The mesh that this bone is attached to.
  72037. * @returns The local position
  72038. */
  72039. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  72040. if (mesh === void 0) { mesh = null; }
  72041. var result = BABYLON.Vector3.Zero();
  72042. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  72043. return result;
  72044. };
  72045. /**
  72046. * Get the local position of a point that is in world space and copy it to the result param.
  72047. * @param position The world position
  72048. * @param mesh The mesh that this bone is attached to.
  72049. * @param result The vector3 that the local position should be copied to.
  72050. */
  72051. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  72052. if (mesh === void 0) { mesh = null; }
  72053. var wm = null;
  72054. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72055. if (mesh) {
  72056. wm = mesh.getWorldMatrix();
  72057. }
  72058. this._skeleton.computeAbsoluteTransforms();
  72059. var tmat = Bone._tmpMats[0];
  72060. tmat.copyFrom(this.getAbsoluteTransform());
  72061. if (mesh && wm) {
  72062. tmat.multiplyToRef(wm, tmat);
  72063. }
  72064. tmat.invert();
  72065. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72066. };
  72067. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72068. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  72069. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72070. return Bone;
  72071. }(BABYLON.Node));
  72072. BABYLON.Bone = Bone;
  72073. })(BABYLON || (BABYLON = {}));
  72074. //# sourceMappingURL=babylon.bone.js.map
  72075. var BABYLON;
  72076. (function (BABYLON) {
  72077. var BoneIKController = /** @class */ (function () {
  72078. function BoneIKController(mesh, bone, options) {
  72079. this.targetPosition = BABYLON.Vector3.Zero();
  72080. this.poleTargetPosition = BABYLON.Vector3.Zero();
  72081. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  72082. this.poleAngle = 0;
  72083. this.slerpAmount = 1;
  72084. this._bone1Quat = BABYLON.Quaternion.Identity();
  72085. this._bone1Mat = BABYLON.Matrix.Identity();
  72086. this._bone2Ang = Math.PI;
  72087. this._maxAngle = Math.PI;
  72088. this._rightHandedSystem = false;
  72089. this._bendAxis = BABYLON.Vector3.Right();
  72090. this._slerping = false;
  72091. this._adjustRoll = 0;
  72092. this._bone2 = bone;
  72093. this._bone1 = bone.getParent();
  72094. if (!this._bone1) {
  72095. return;
  72096. }
  72097. this.mesh = mesh;
  72098. var bonePos = bone.getPosition();
  72099. if (bone.getAbsoluteTransform().determinant() > 0) {
  72100. this._rightHandedSystem = true;
  72101. this._bendAxis.x = 0;
  72102. this._bendAxis.y = 0;
  72103. this._bendAxis.z = -1;
  72104. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  72105. this._adjustRoll = Math.PI * .5;
  72106. this._bendAxis.z = 1;
  72107. }
  72108. }
  72109. if (this._bone1.length) {
  72110. var boneScale1 = this._bone1.getScale();
  72111. var boneScale2 = this._bone2.getScale();
  72112. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  72113. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  72114. }
  72115. else if (this._bone1.children[0]) {
  72116. mesh.computeWorldMatrix(true);
  72117. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  72118. var pos2 = this._bone2.getAbsolutePosition(mesh);
  72119. var pos3 = this._bone1.getAbsolutePosition(mesh);
  72120. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  72121. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  72122. }
  72123. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  72124. this.maxAngle = Math.PI;
  72125. if (options) {
  72126. if (options.targetMesh) {
  72127. this.targetMesh = options.targetMesh;
  72128. this.targetMesh.computeWorldMatrix(true);
  72129. }
  72130. if (options.poleTargetMesh) {
  72131. this.poleTargetMesh = options.poleTargetMesh;
  72132. this.poleTargetMesh.computeWorldMatrix(true);
  72133. }
  72134. else if (options.poleTargetBone) {
  72135. this.poleTargetBone = options.poleTargetBone;
  72136. }
  72137. else if (this._bone1.getParent()) {
  72138. this.poleTargetBone = this._bone1.getParent();
  72139. }
  72140. if (options.poleTargetLocalOffset) {
  72141. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  72142. }
  72143. if (options.poleAngle) {
  72144. this.poleAngle = options.poleAngle;
  72145. }
  72146. if (options.bendAxis) {
  72147. this._bendAxis.copyFrom(options.bendAxis);
  72148. }
  72149. if (options.maxAngle) {
  72150. this.maxAngle = options.maxAngle;
  72151. }
  72152. if (options.slerpAmount) {
  72153. this.slerpAmount = options.slerpAmount;
  72154. }
  72155. }
  72156. }
  72157. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  72158. get: function () {
  72159. return this._maxAngle;
  72160. },
  72161. set: function (value) {
  72162. this._setMaxAngle(value);
  72163. },
  72164. enumerable: true,
  72165. configurable: true
  72166. });
  72167. BoneIKController.prototype._setMaxAngle = function (ang) {
  72168. if (ang < 0) {
  72169. ang = 0;
  72170. }
  72171. if (ang > Math.PI || ang == undefined) {
  72172. ang = Math.PI;
  72173. }
  72174. this._maxAngle = ang;
  72175. var a = this._bone1Length;
  72176. var b = this._bone2Length;
  72177. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  72178. };
  72179. BoneIKController.prototype.update = function () {
  72180. var bone1 = this._bone1;
  72181. if (!bone1) {
  72182. return;
  72183. }
  72184. var target = this.targetPosition;
  72185. var poleTarget = this.poleTargetPosition;
  72186. var mat1 = BoneIKController._tmpMats[0];
  72187. var mat2 = BoneIKController._tmpMats[1];
  72188. if (this.targetMesh) {
  72189. target.copyFrom(this.targetMesh.getAbsolutePosition());
  72190. }
  72191. if (this.poleTargetBone) {
  72192. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  72193. }
  72194. else if (this.poleTargetMesh) {
  72195. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  72196. }
  72197. var bonePos = BoneIKController._tmpVecs[0];
  72198. var zaxis = BoneIKController._tmpVecs[1];
  72199. var xaxis = BoneIKController._tmpVecs[2];
  72200. var yaxis = BoneIKController._tmpVecs[3];
  72201. var upAxis = BoneIKController._tmpVecs[4];
  72202. var _tmpQuat = BoneIKController._tmpQuat;
  72203. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  72204. poleTarget.subtractToRef(bonePos, upAxis);
  72205. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  72206. upAxis.y = 1;
  72207. }
  72208. else {
  72209. upAxis.normalize();
  72210. }
  72211. target.subtractToRef(bonePos, yaxis);
  72212. yaxis.normalize();
  72213. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  72214. zaxis.normalize();
  72215. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  72216. xaxis.normalize();
  72217. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  72218. var a = this._bone1Length;
  72219. var b = this._bone2Length;
  72220. var c = BABYLON.Vector3.Distance(bonePos, target);
  72221. if (this._maxReach > 0) {
  72222. c = Math.min(this._maxReach, c);
  72223. }
  72224. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  72225. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  72226. if (acosa > 1) {
  72227. acosa = 1;
  72228. }
  72229. if (acosb > 1) {
  72230. acosb = 1;
  72231. }
  72232. if (acosa < -1) {
  72233. acosa = -1;
  72234. }
  72235. if (acosb < -1) {
  72236. acosb = -1;
  72237. }
  72238. var angA = Math.acos(acosa);
  72239. var angB = Math.acos(acosb);
  72240. var angC = -angA - angB;
  72241. if (this._rightHandedSystem) {
  72242. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  72243. mat2.multiplyToRef(mat1, mat1);
  72244. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  72245. mat2.multiplyToRef(mat1, mat1);
  72246. }
  72247. else {
  72248. var _tmpVec = BoneIKController._tmpVecs[5];
  72249. _tmpVec.copyFrom(this._bendAxis);
  72250. _tmpVec.x *= -1;
  72251. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  72252. mat2.multiplyToRef(mat1, mat1);
  72253. }
  72254. if (this.poleAngle) {
  72255. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  72256. mat1.multiplyToRef(mat2, mat1);
  72257. }
  72258. if (this._bone1) {
  72259. if (this.slerpAmount < 1) {
  72260. if (!this._slerping) {
  72261. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  72262. }
  72263. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  72264. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  72265. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  72266. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  72267. this._slerping = true;
  72268. }
  72269. else {
  72270. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  72271. this._bone1Mat.copyFrom(mat1);
  72272. this._slerping = false;
  72273. }
  72274. }
  72275. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  72276. this._bone2Ang = angC;
  72277. };
  72278. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72279. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  72280. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72281. return BoneIKController;
  72282. }());
  72283. BABYLON.BoneIKController = BoneIKController;
  72284. })(BABYLON || (BABYLON = {}));
  72285. //# sourceMappingURL=babylon.boneIKController.js.map
  72286. var BABYLON;
  72287. (function (BABYLON) {
  72288. var BoneLookController = /** @class */ (function () {
  72289. /**
  72290. * Create a BoneLookController
  72291. * @param mesh the mesh that the bone belongs to
  72292. * @param bone the bone that will be looking to the target
  72293. * @param target the target Vector3 to look at
  72294. * @param settings optional settings:
  72295. * - maxYaw: the maximum angle the bone will yaw to
  72296. * - minYaw: the minimum angle the bone will yaw to
  72297. * - maxPitch: the maximum angle the bone will pitch to
  72298. * - minPitch: the minimum angle the bone will yaw to
  72299. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  72300. * - upAxis: the up axis of the coordinate system
  72301. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72302. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  72303. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  72304. * - adjustYaw: used to make an adjustment to the yaw of the bone
  72305. * - adjustPitch: used to make an adjustment to the pitch of the bone
  72306. * - adjustRoll: used to make an adjustment to the roll of the bone
  72307. **/
  72308. function BoneLookController(mesh, bone, target, options) {
  72309. /**
  72310. * The up axis of the coordinate system that is used when the bone is rotated.
  72311. */
  72312. this.upAxis = BABYLON.Vector3.Up();
  72313. /**
  72314. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72315. */
  72316. this.upAxisSpace = BABYLON.Space.LOCAL;
  72317. /**
  72318. * Used to make an adjustment to the yaw of the bone.
  72319. */
  72320. this.adjustYaw = 0;
  72321. /**
  72322. * Used to make an adjustment to the pitch of the bone.
  72323. */
  72324. this.adjustPitch = 0;
  72325. /**
  72326. * Used to make an adjustment to the roll of the bone.
  72327. */
  72328. this.adjustRoll = 0;
  72329. /**
  72330. * 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).
  72331. */
  72332. this.slerpAmount = 1;
  72333. this._boneQuat = BABYLON.Quaternion.Identity();
  72334. this._slerping = false;
  72335. this._firstFrameSkipped = false;
  72336. this._fowardAxis = BABYLON.Vector3.Forward();
  72337. this.mesh = mesh;
  72338. this.bone = bone;
  72339. this.target = target;
  72340. if (options) {
  72341. if (options.adjustYaw) {
  72342. this.adjustYaw = options.adjustYaw;
  72343. }
  72344. if (options.adjustPitch) {
  72345. this.adjustPitch = options.adjustPitch;
  72346. }
  72347. if (options.adjustRoll) {
  72348. this.adjustRoll = options.adjustRoll;
  72349. }
  72350. if (options.maxYaw != null) {
  72351. this.maxYaw = options.maxYaw;
  72352. }
  72353. else {
  72354. this.maxYaw = Math.PI;
  72355. }
  72356. if (options.minYaw != null) {
  72357. this.minYaw = options.minYaw;
  72358. }
  72359. else {
  72360. this.minYaw = -Math.PI;
  72361. }
  72362. if (options.maxPitch != null) {
  72363. this.maxPitch = options.maxPitch;
  72364. }
  72365. else {
  72366. this.maxPitch = Math.PI;
  72367. }
  72368. if (options.minPitch != null) {
  72369. this.minPitch = options.minPitch;
  72370. }
  72371. else {
  72372. this.minPitch = -Math.PI;
  72373. }
  72374. if (options.slerpAmount != null) {
  72375. this.slerpAmount = options.slerpAmount;
  72376. }
  72377. if (options.upAxis != null) {
  72378. this.upAxis = options.upAxis;
  72379. }
  72380. if (options.upAxisSpace != null) {
  72381. this.upAxisSpace = options.upAxisSpace;
  72382. }
  72383. if (options.yawAxis != null || options.pitchAxis != null) {
  72384. var newYawAxis = BABYLON.Axis.Y;
  72385. var newPitchAxis = BABYLON.Axis.X;
  72386. if (options.yawAxis != null) {
  72387. newYawAxis = options.yawAxis.clone();
  72388. newYawAxis.normalize();
  72389. }
  72390. if (options.pitchAxis != null) {
  72391. newPitchAxis = options.pitchAxis.clone();
  72392. newPitchAxis.normalize();
  72393. }
  72394. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  72395. this._transformYawPitch = BABYLON.Matrix.Identity();
  72396. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  72397. this._transformYawPitchInv = this._transformYawPitch.clone();
  72398. this._transformYawPitch.invert();
  72399. }
  72400. }
  72401. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  72402. this.upAxisSpace = BABYLON.Space.LOCAL;
  72403. }
  72404. }
  72405. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  72406. /**
  72407. * Get/set the minimum yaw angle that the bone can look to.
  72408. */
  72409. get: function () {
  72410. return this._minYaw;
  72411. },
  72412. set: function (value) {
  72413. this._minYaw = value;
  72414. this._minYawSin = Math.sin(value);
  72415. this._minYawCos = Math.cos(value);
  72416. if (this._maxYaw != null) {
  72417. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72418. this._yawRange = this._maxYaw - this._minYaw;
  72419. }
  72420. },
  72421. enumerable: true,
  72422. configurable: true
  72423. });
  72424. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  72425. /**
  72426. * Get/set the maximum yaw angle that the bone can look to.
  72427. */
  72428. get: function () {
  72429. return this._maxYaw;
  72430. },
  72431. set: function (value) {
  72432. this._maxYaw = value;
  72433. this._maxYawSin = Math.sin(value);
  72434. this._maxYawCos = Math.cos(value);
  72435. if (this._minYaw != null) {
  72436. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72437. this._yawRange = this._maxYaw - this._minYaw;
  72438. }
  72439. },
  72440. enumerable: true,
  72441. configurable: true
  72442. });
  72443. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  72444. /**
  72445. * Get/set the minimum pitch angle that the bone can look to.
  72446. */
  72447. get: function () {
  72448. return this._minPitch;
  72449. },
  72450. set: function (value) {
  72451. this._minPitch = value;
  72452. this._minPitchTan = Math.tan(value);
  72453. },
  72454. enumerable: true,
  72455. configurable: true
  72456. });
  72457. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  72458. /**
  72459. * Get/set the maximum pitch angle that the bone can look to.
  72460. */
  72461. get: function () {
  72462. return this._maxPitch;
  72463. },
  72464. set: function (value) {
  72465. this._maxPitch = value;
  72466. this._maxPitchTan = Math.tan(value);
  72467. },
  72468. enumerable: true,
  72469. configurable: true
  72470. });
  72471. /**
  72472. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  72473. */
  72474. BoneLookController.prototype.update = function () {
  72475. //skip the first frame when slerping so that the mesh rotation is correct
  72476. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  72477. this._firstFrameSkipped = true;
  72478. return;
  72479. }
  72480. var bone = this.bone;
  72481. var bonePos = BoneLookController._tmpVecs[0];
  72482. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  72483. var target = this.target;
  72484. var _tmpMat1 = BoneLookController._tmpMats[0];
  72485. var _tmpMat2 = BoneLookController._tmpMats[1];
  72486. var mesh = this.mesh;
  72487. var parentBone = bone.getParent();
  72488. var upAxis = BoneLookController._tmpVecs[1];
  72489. upAxis.copyFrom(this.upAxis);
  72490. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  72491. if (this._transformYawPitch) {
  72492. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  72493. }
  72494. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  72495. }
  72496. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  72497. mesh.getDirectionToRef(upAxis, upAxis);
  72498. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  72499. upAxis.normalize();
  72500. }
  72501. }
  72502. var checkYaw = false;
  72503. var checkPitch = false;
  72504. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  72505. checkYaw = true;
  72506. }
  72507. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  72508. checkPitch = true;
  72509. }
  72510. if (checkYaw || checkPitch) {
  72511. var spaceMat = BoneLookController._tmpMats[2];
  72512. var spaceMatInv = BoneLookController._tmpMats[3];
  72513. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  72514. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  72515. }
  72516. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  72517. spaceMat.copyFrom(mesh.getWorldMatrix());
  72518. }
  72519. else {
  72520. var forwardAxis = BoneLookController._tmpVecs[2];
  72521. forwardAxis.copyFrom(this._fowardAxis);
  72522. if (this._transformYawPitch) {
  72523. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  72524. }
  72525. if (parentBone) {
  72526. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  72527. }
  72528. else {
  72529. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  72530. }
  72531. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  72532. rightAxis.normalize();
  72533. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  72534. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  72535. }
  72536. spaceMat.invertToRef(spaceMatInv);
  72537. var xzlen = null;
  72538. if (checkPitch) {
  72539. var localTarget = BoneLookController._tmpVecs[3];
  72540. target.subtractToRef(bonePos, localTarget);
  72541. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72542. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72543. var pitch = Math.atan2(localTarget.y, xzlen);
  72544. var newPitch = pitch;
  72545. if (pitch > this._maxPitch) {
  72546. localTarget.y = this._maxPitchTan * xzlen;
  72547. newPitch = this._maxPitch;
  72548. }
  72549. else if (pitch < this._minPitch) {
  72550. localTarget.y = this._minPitchTan * xzlen;
  72551. newPitch = this._minPitch;
  72552. }
  72553. if (pitch != newPitch) {
  72554. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72555. localTarget.addInPlace(bonePos);
  72556. target = localTarget;
  72557. }
  72558. }
  72559. if (checkYaw) {
  72560. var localTarget = BoneLookController._tmpVecs[4];
  72561. target.subtractToRef(bonePos, localTarget);
  72562. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72563. var yaw = Math.atan2(localTarget.x, localTarget.z);
  72564. var newYaw = yaw;
  72565. if (yaw > this._maxYaw || yaw < this._minYaw) {
  72566. if (xzlen == null) {
  72567. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72568. }
  72569. if (this._yawRange > Math.PI) {
  72570. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  72571. localTarget.z = this._maxYawCos * xzlen;
  72572. localTarget.x = this._maxYawSin * xzlen;
  72573. newYaw = this._maxYaw;
  72574. }
  72575. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  72576. localTarget.z = this._minYawCos * xzlen;
  72577. localTarget.x = this._minYawSin * xzlen;
  72578. newYaw = this._minYaw;
  72579. }
  72580. }
  72581. else {
  72582. if (yaw > this._maxYaw) {
  72583. localTarget.z = this._maxYawCos * xzlen;
  72584. localTarget.x = this._maxYawSin * xzlen;
  72585. newYaw = this._maxYaw;
  72586. }
  72587. else if (yaw < this._minYaw) {
  72588. localTarget.z = this._minYawCos * xzlen;
  72589. localTarget.x = this._minYawSin * xzlen;
  72590. newYaw = this._minYaw;
  72591. }
  72592. }
  72593. }
  72594. if (this._slerping && this._yawRange > Math.PI) {
  72595. //are we going to be crossing into the min/max region?
  72596. var boneFwd = BoneLookController._tmpVecs[8];
  72597. boneFwd.copyFrom(BABYLON.Axis.Z);
  72598. if (this._transformYawPitch) {
  72599. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  72600. }
  72601. var boneRotMat = BoneLookController._tmpMats[4];
  72602. this._boneQuat.toRotationMatrix(boneRotMat);
  72603. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  72604. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  72605. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  72606. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  72607. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  72608. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  72609. if (angBtwTar > angBtwMidYaw) {
  72610. if (xzlen == null) {
  72611. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72612. }
  72613. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  72614. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  72615. if (angBtwMin < angBtwMax) {
  72616. newYaw = boneYaw + Math.PI * .75;
  72617. localTarget.z = Math.cos(newYaw) * xzlen;
  72618. localTarget.x = Math.sin(newYaw) * xzlen;
  72619. }
  72620. else {
  72621. newYaw = boneYaw - Math.PI * .75;
  72622. localTarget.z = Math.cos(newYaw) * xzlen;
  72623. localTarget.x = Math.sin(newYaw) * xzlen;
  72624. }
  72625. }
  72626. }
  72627. if (yaw != newYaw) {
  72628. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72629. localTarget.addInPlace(bonePos);
  72630. target = localTarget;
  72631. }
  72632. }
  72633. }
  72634. var zaxis = BoneLookController._tmpVecs[5];
  72635. var xaxis = BoneLookController._tmpVecs[6];
  72636. var yaxis = BoneLookController._tmpVecs[7];
  72637. var _tmpQuat = BoneLookController._tmpQuat;
  72638. target.subtractToRef(bonePos, zaxis);
  72639. zaxis.normalize();
  72640. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  72641. xaxis.normalize();
  72642. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  72643. yaxis.normalize();
  72644. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  72645. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  72646. return;
  72647. }
  72648. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  72649. return;
  72650. }
  72651. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  72652. return;
  72653. }
  72654. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  72655. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  72656. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  72657. }
  72658. if (this.slerpAmount < 1) {
  72659. if (!this._slerping) {
  72660. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  72661. }
  72662. if (this._transformYawPitch) {
  72663. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72664. }
  72665. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  72666. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  72667. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  72668. this._slerping = true;
  72669. }
  72670. else {
  72671. if (this._transformYawPitch) {
  72672. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72673. }
  72674. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  72675. this._slerping = false;
  72676. }
  72677. };
  72678. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  72679. var angDiff = ang2 - ang1;
  72680. angDiff %= Math.PI * 2;
  72681. if (angDiff > Math.PI) {
  72682. angDiff -= Math.PI * 2;
  72683. }
  72684. else if (angDiff < -Math.PI) {
  72685. angDiff += Math.PI * 2;
  72686. }
  72687. return angDiff;
  72688. };
  72689. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  72690. ang1 %= (2 * Math.PI);
  72691. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72692. ang2 %= (2 * Math.PI);
  72693. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72694. var ab = 0;
  72695. if (ang1 < ang2) {
  72696. ab = ang2 - ang1;
  72697. }
  72698. else {
  72699. ab = ang1 - ang2;
  72700. }
  72701. if (ab > Math.PI) {
  72702. ab = Math.PI * 2 - ab;
  72703. }
  72704. return ab;
  72705. };
  72706. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  72707. ang %= (2 * Math.PI);
  72708. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  72709. ang1 %= (2 * Math.PI);
  72710. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72711. ang2 %= (2 * Math.PI);
  72712. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72713. if (ang1 < ang2) {
  72714. if (ang > ang1 && ang < ang2) {
  72715. return true;
  72716. }
  72717. }
  72718. else {
  72719. if (ang > ang2 && ang < ang1) {
  72720. return true;
  72721. }
  72722. }
  72723. return false;
  72724. };
  72725. 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()];
  72726. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  72727. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72728. return BoneLookController;
  72729. }());
  72730. BABYLON.BoneLookController = BoneLookController;
  72731. })(BABYLON || (BABYLON = {}));
  72732. //# sourceMappingURL=babylon.boneLookController.js.map
  72733. var BABYLON;
  72734. (function (BABYLON) {
  72735. var Skeleton = /** @class */ (function () {
  72736. function Skeleton(name, id, scene) {
  72737. this.name = name;
  72738. this.id = id;
  72739. this.bones = new Array();
  72740. this.needInitialSkinMatrix = false;
  72741. this._isDirty = true;
  72742. this._meshesWithPoseMatrix = new Array();
  72743. this._identity = BABYLON.Matrix.Identity();
  72744. this._ranges = {};
  72745. this._lastAbsoluteTransformsUpdateId = -1;
  72746. /**
  72747. * Specifies if the skeleton should be serialized.
  72748. */
  72749. this.doNotSerialize = false;
  72750. // Events
  72751. /**
  72752. * An event triggered before computing the skeleton's matrices
  72753. * @type {BABYLON.Observable}
  72754. */
  72755. this.onBeforeComputeObservable = new BABYLON.Observable();
  72756. this.bones = [];
  72757. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72758. scene.skeletons.push(this);
  72759. //make sure it will recalculate the matrix next time prepare is called.
  72760. this._isDirty = true;
  72761. }
  72762. // Members
  72763. Skeleton.prototype.getTransformMatrices = function (mesh) {
  72764. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  72765. return mesh._bonesTransformMatrices;
  72766. }
  72767. if (!this._transformMatrices) {
  72768. this.prepare();
  72769. }
  72770. return this._transformMatrices;
  72771. };
  72772. Skeleton.prototype.getScene = function () {
  72773. return this._scene;
  72774. };
  72775. // Methods
  72776. /**
  72777. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  72778. */
  72779. Skeleton.prototype.toString = function (fullDetails) {
  72780. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  72781. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  72782. if (fullDetails) {
  72783. ret += ", Ranges: {";
  72784. var first = true;
  72785. for (var name_1 in this._ranges) {
  72786. if (first) {
  72787. ret += ", ";
  72788. first = false;
  72789. }
  72790. ret += name_1;
  72791. }
  72792. ret += "}";
  72793. }
  72794. return ret;
  72795. };
  72796. /**
  72797. * Get bone's index searching by name
  72798. * @param {string} name is bone's name to search for
  72799. * @return {number} Indice of the bone. Returns -1 if not found
  72800. */
  72801. Skeleton.prototype.getBoneIndexByName = function (name) {
  72802. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  72803. if (this.bones[boneIndex].name === name) {
  72804. return boneIndex;
  72805. }
  72806. }
  72807. return -1;
  72808. };
  72809. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  72810. // check name not already in use
  72811. if (!this._ranges[name]) {
  72812. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  72813. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72814. if (this.bones[i].animations[0]) {
  72815. this.bones[i].animations[0].createRange(name, from, to);
  72816. }
  72817. }
  72818. }
  72819. };
  72820. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  72821. if (deleteFrames === void 0) { deleteFrames = true; }
  72822. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72823. if (this.bones[i].animations[0]) {
  72824. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  72825. }
  72826. }
  72827. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  72828. };
  72829. Skeleton.prototype.getAnimationRange = function (name) {
  72830. return this._ranges[name];
  72831. };
  72832. /**
  72833. * Returns as an Array, all AnimationRanges defined on this skeleton
  72834. */
  72835. Skeleton.prototype.getAnimationRanges = function () {
  72836. var animationRanges = [];
  72837. var name;
  72838. var i = 0;
  72839. for (name in this._ranges) {
  72840. animationRanges[i] = this._ranges[name];
  72841. i++;
  72842. }
  72843. return animationRanges;
  72844. };
  72845. /**
  72846. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  72847. */
  72848. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  72849. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72850. if (this._ranges[name] || !source.getAnimationRange(name)) {
  72851. return false;
  72852. }
  72853. var ret = true;
  72854. var frameOffset = this._getHighestAnimationFrame() + 1;
  72855. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  72856. var boneDict = {};
  72857. var sourceBones = source.bones;
  72858. var nBones;
  72859. var i;
  72860. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  72861. boneDict[sourceBones[i].name] = sourceBones[i];
  72862. }
  72863. if (this.bones.length !== sourceBones.length) {
  72864. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  72865. ret = false;
  72866. }
  72867. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  72868. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  72869. var boneName = this.bones[i].name;
  72870. var sourceBone = boneDict[boneName];
  72871. if (sourceBone) {
  72872. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  72873. }
  72874. else {
  72875. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  72876. ret = false;
  72877. }
  72878. }
  72879. // do not call createAnimationRange(), since it also is done to bones, which was already done
  72880. var range = source.getAnimationRange(name);
  72881. if (range) {
  72882. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  72883. }
  72884. return ret;
  72885. };
  72886. Skeleton.prototype.returnToRest = function () {
  72887. for (var index = 0; index < this.bones.length; index++) {
  72888. this.bones[index].returnToRest();
  72889. }
  72890. };
  72891. Skeleton.prototype._getHighestAnimationFrame = function () {
  72892. var ret = 0;
  72893. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72894. if (this.bones[i].animations[0]) {
  72895. var highest = this.bones[i].animations[0].getHighestFrame();
  72896. if (ret < highest) {
  72897. ret = highest;
  72898. }
  72899. }
  72900. }
  72901. return ret;
  72902. };
  72903. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  72904. var range = this.getAnimationRange(name);
  72905. if (!range) {
  72906. return null;
  72907. }
  72908. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  72909. };
  72910. Skeleton.prototype._markAsDirty = function () {
  72911. this._isDirty = true;
  72912. };
  72913. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  72914. this._meshesWithPoseMatrix.push(mesh);
  72915. };
  72916. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  72917. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  72918. if (index > -1) {
  72919. this._meshesWithPoseMatrix.splice(index, 1);
  72920. }
  72921. };
  72922. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  72923. this.onBeforeComputeObservable.notifyObservers(this);
  72924. for (var index = 0; index < this.bones.length; index++) {
  72925. var bone = this.bones[index];
  72926. var parentBone = bone.getParent();
  72927. if (parentBone) {
  72928. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  72929. }
  72930. else {
  72931. if (initialSkinMatrix) {
  72932. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  72933. }
  72934. else {
  72935. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  72936. }
  72937. }
  72938. if (bone._index !== -1) {
  72939. var mappedIndex = bone._index === null ? index : bone._index;
  72940. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  72941. }
  72942. }
  72943. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  72944. };
  72945. Skeleton.prototype.prepare = function () {
  72946. if (!this._isDirty) {
  72947. return;
  72948. }
  72949. if (this.needInitialSkinMatrix) {
  72950. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  72951. var mesh = this._meshesWithPoseMatrix[index];
  72952. var poseMatrix = mesh.getPoseMatrix();
  72953. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  72954. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72955. }
  72956. if (this._synchronizedWithMesh !== mesh) {
  72957. this._synchronizedWithMesh = mesh;
  72958. // Prepare bones
  72959. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  72960. var bone = this.bones[boneIndex];
  72961. if (!bone.getParent()) {
  72962. var matrix = bone.getBaseMatrix();
  72963. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  72964. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  72965. }
  72966. }
  72967. }
  72968. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  72969. }
  72970. }
  72971. else {
  72972. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  72973. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72974. }
  72975. this._computeTransformMatrices(this._transformMatrices, null);
  72976. }
  72977. this._isDirty = false;
  72978. this._scene._activeBones.addCount(this.bones.length, false);
  72979. };
  72980. Skeleton.prototype.getAnimatables = function () {
  72981. if (!this._animatables || this._animatables.length !== this.bones.length) {
  72982. this._animatables = [];
  72983. for (var index = 0; index < this.bones.length; index++) {
  72984. this._animatables.push(this.bones[index]);
  72985. }
  72986. }
  72987. return this._animatables;
  72988. };
  72989. Skeleton.prototype.clone = function (name, id) {
  72990. var result = new Skeleton(name, id || name, this._scene);
  72991. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72992. for (var index = 0; index < this.bones.length; index++) {
  72993. var source = this.bones[index];
  72994. var parentBone = null;
  72995. var parent_1 = source.getParent();
  72996. if (parent_1) {
  72997. var parentIndex = this.bones.indexOf(parent_1);
  72998. parentBone = result.bones[parentIndex];
  72999. }
  73000. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  73001. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  73002. }
  73003. if (this._ranges) {
  73004. result._ranges = {};
  73005. for (var rangeName in this._ranges) {
  73006. var range = this._ranges[rangeName];
  73007. if (range) {
  73008. result._ranges[rangeName] = range.clone();
  73009. }
  73010. }
  73011. }
  73012. this._isDirty = true;
  73013. return result;
  73014. };
  73015. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  73016. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  73017. this.bones.forEach(function (bone) {
  73018. bone.animations.forEach(function (animation) {
  73019. animation.enableBlending = true;
  73020. animation.blendingSpeed = blendingSpeed;
  73021. });
  73022. });
  73023. };
  73024. Skeleton.prototype.dispose = function () {
  73025. this._meshesWithPoseMatrix = [];
  73026. // Animations
  73027. this.getScene().stopAnimation(this);
  73028. // Remove from scene
  73029. this.getScene().removeSkeleton(this);
  73030. };
  73031. Skeleton.prototype.serialize = function () {
  73032. var serializationObject = {};
  73033. serializationObject.name = this.name;
  73034. serializationObject.id = this.id;
  73035. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  73036. serializationObject.bones = [];
  73037. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73038. for (var index = 0; index < this.bones.length; index++) {
  73039. var bone = this.bones[index];
  73040. var parent_2 = bone.getParent();
  73041. var serializedBone = {
  73042. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  73043. name: bone.name,
  73044. matrix: bone.getBaseMatrix().toArray(),
  73045. rest: bone.getRestPose().toArray()
  73046. };
  73047. serializationObject.bones.push(serializedBone);
  73048. if (bone.length) {
  73049. serializedBone.length = bone.length;
  73050. }
  73051. if (bone.animations && bone.animations.length > 0) {
  73052. serializedBone.animation = bone.animations[0].serialize();
  73053. }
  73054. serializationObject.ranges = [];
  73055. for (var name in this._ranges) {
  73056. var source = this._ranges[name];
  73057. if (!source) {
  73058. continue;
  73059. }
  73060. var range = {};
  73061. range.name = name;
  73062. range.from = source.from;
  73063. range.to = source.to;
  73064. serializationObject.ranges.push(range);
  73065. }
  73066. }
  73067. return serializationObject;
  73068. };
  73069. Skeleton.Parse = function (parsedSkeleton, scene) {
  73070. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  73071. if (parsedSkeleton.dimensionsAtRest) {
  73072. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  73073. }
  73074. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  73075. var index;
  73076. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  73077. var parsedBone = parsedSkeleton.bones[index];
  73078. var parentBone = null;
  73079. if (parsedBone.parentBoneIndex > -1) {
  73080. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  73081. }
  73082. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  73083. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  73084. if (parsedBone.length) {
  73085. bone.length = parsedBone.length;
  73086. }
  73087. if (parsedBone.animation) {
  73088. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  73089. }
  73090. }
  73091. // placed after bones, so createAnimationRange can cascade down
  73092. if (parsedSkeleton.ranges) {
  73093. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  73094. var data = parsedSkeleton.ranges[index];
  73095. skeleton.createAnimationRange(data.name, data.from, data.to);
  73096. }
  73097. }
  73098. return skeleton;
  73099. };
  73100. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  73101. if (forceUpdate === void 0) { forceUpdate = false; }
  73102. var renderId = this._scene.getRenderId();
  73103. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  73104. this.bones[0].computeAbsoluteTransforms();
  73105. this._lastAbsoluteTransformsUpdateId = renderId;
  73106. }
  73107. };
  73108. Skeleton.prototype.getPoseMatrix = function () {
  73109. var poseMatrix = null;
  73110. if (this._meshesWithPoseMatrix.length > 0) {
  73111. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  73112. }
  73113. return poseMatrix;
  73114. };
  73115. Skeleton.prototype.sortBones = function () {
  73116. var bones = new Array();
  73117. var visited = new Array(this.bones.length);
  73118. for (var index = 0; index < this.bones.length; index++) {
  73119. this._sortBones(index, bones, visited);
  73120. }
  73121. this.bones = bones;
  73122. };
  73123. Skeleton.prototype._sortBones = function (index, bones, visited) {
  73124. if (visited[index]) {
  73125. return;
  73126. }
  73127. visited[index] = true;
  73128. var bone = this.bones[index];
  73129. if (bone._index === undefined) {
  73130. bone._index = index;
  73131. }
  73132. var parentBone = bone.getParent();
  73133. if (parentBone) {
  73134. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  73135. }
  73136. bones.push(bone);
  73137. };
  73138. return Skeleton;
  73139. }());
  73140. BABYLON.Skeleton = Skeleton;
  73141. })(BABYLON || (BABYLON = {}));
  73142. //# sourceMappingURL=babylon.skeleton.js.map
  73143. var BABYLON;
  73144. (function (BABYLON) {
  73145. var SphericalPolynomial = /** @class */ (function () {
  73146. function SphericalPolynomial() {
  73147. this.x = BABYLON.Vector3.Zero();
  73148. this.y = BABYLON.Vector3.Zero();
  73149. this.z = BABYLON.Vector3.Zero();
  73150. this.xx = BABYLON.Vector3.Zero();
  73151. this.yy = BABYLON.Vector3.Zero();
  73152. this.zz = BABYLON.Vector3.Zero();
  73153. this.xy = BABYLON.Vector3.Zero();
  73154. this.yz = BABYLON.Vector3.Zero();
  73155. this.zx = BABYLON.Vector3.Zero();
  73156. }
  73157. SphericalPolynomial.prototype.addAmbient = function (color) {
  73158. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73159. this.xx = this.xx.add(colorVector);
  73160. this.yy = this.yy.add(colorVector);
  73161. this.zz = this.zz.add(colorVector);
  73162. };
  73163. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  73164. var result = new SphericalPolynomial();
  73165. result.x = harmonics.L11.scale(1.02333);
  73166. result.y = harmonics.L1_1.scale(1.02333);
  73167. result.z = harmonics.L10.scale(1.02333);
  73168. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  73169. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  73170. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  73171. result.yz = harmonics.L2_1.scale(0.858086);
  73172. result.zx = harmonics.L21.scale(0.858086);
  73173. result.xy = harmonics.L2_2.scale(0.858086);
  73174. result.scale(1.0 / Math.PI);
  73175. return result;
  73176. };
  73177. SphericalPolynomial.prototype.scale = function (scale) {
  73178. this.x = this.x.scale(scale);
  73179. this.y = this.y.scale(scale);
  73180. this.z = this.z.scale(scale);
  73181. this.xx = this.xx.scale(scale);
  73182. this.yy = this.yy.scale(scale);
  73183. this.zz = this.zz.scale(scale);
  73184. this.yz = this.yz.scale(scale);
  73185. this.zx = this.zx.scale(scale);
  73186. this.xy = this.xy.scale(scale);
  73187. };
  73188. return SphericalPolynomial;
  73189. }());
  73190. BABYLON.SphericalPolynomial = SphericalPolynomial;
  73191. var SphericalHarmonics = /** @class */ (function () {
  73192. function SphericalHarmonics() {
  73193. this.L00 = BABYLON.Vector3.Zero();
  73194. this.L1_1 = BABYLON.Vector3.Zero();
  73195. this.L10 = BABYLON.Vector3.Zero();
  73196. this.L11 = BABYLON.Vector3.Zero();
  73197. this.L2_2 = BABYLON.Vector3.Zero();
  73198. this.L2_1 = BABYLON.Vector3.Zero();
  73199. this.L20 = BABYLON.Vector3.Zero();
  73200. this.L21 = BABYLON.Vector3.Zero();
  73201. this.L22 = BABYLON.Vector3.Zero();
  73202. }
  73203. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  73204. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73205. var c = colorVector.scale(deltaSolidAngle);
  73206. this.L00 = this.L00.add(c.scale(0.282095));
  73207. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  73208. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  73209. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  73210. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  73211. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  73212. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  73213. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  73214. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  73215. };
  73216. SphericalHarmonics.prototype.scale = function (scale) {
  73217. this.L00 = this.L00.scale(scale);
  73218. this.L1_1 = this.L1_1.scale(scale);
  73219. this.L10 = this.L10.scale(scale);
  73220. this.L11 = this.L11.scale(scale);
  73221. this.L2_2 = this.L2_2.scale(scale);
  73222. this.L2_1 = this.L2_1.scale(scale);
  73223. this.L20 = this.L20.scale(scale);
  73224. this.L21 = this.L21.scale(scale);
  73225. this.L22 = this.L22.scale(scale);
  73226. };
  73227. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  73228. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  73229. //
  73230. // E_lm = A_l * L_lm
  73231. //
  73232. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  73233. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  73234. // the scaling factors are given in equation 9.
  73235. // Constant (Band 0)
  73236. this.L00 = this.L00.scale(3.141593);
  73237. // Linear (Band 1)
  73238. this.L1_1 = this.L1_1.scale(2.094395);
  73239. this.L10 = this.L10.scale(2.094395);
  73240. this.L11 = this.L11.scale(2.094395);
  73241. // Quadratic (Band 2)
  73242. this.L2_2 = this.L2_2.scale(0.785398);
  73243. this.L2_1 = this.L2_1.scale(0.785398);
  73244. this.L20 = this.L20.scale(0.785398);
  73245. this.L21 = this.L21.scale(0.785398);
  73246. this.L22 = this.L22.scale(0.785398);
  73247. };
  73248. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  73249. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  73250. // L = (1/pi) * E * rho
  73251. //
  73252. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  73253. this.scale(1.0 / Math.PI);
  73254. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  73255. // (The pixel shader must apply albedo after texture fetches, etc).
  73256. };
  73257. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  73258. var result = new SphericalHarmonics();
  73259. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  73260. result.L1_1 = polynomial.y.scale(0.977204);
  73261. result.L10 = polynomial.z.scale(0.977204);
  73262. result.L11 = polynomial.x.scale(0.977204);
  73263. result.L2_2 = polynomial.xy.scale(1.16538);
  73264. result.L2_1 = polynomial.yz.scale(1.16538);
  73265. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  73266. result.L21 = polynomial.zx.scale(1.16538);
  73267. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  73268. result.scale(Math.PI);
  73269. return result;
  73270. };
  73271. return SphericalHarmonics;
  73272. }());
  73273. BABYLON.SphericalHarmonics = SphericalHarmonics;
  73274. })(BABYLON || (BABYLON = {}));
  73275. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  73276. var BABYLON;
  73277. (function (BABYLON) {
  73278. var FileFaceOrientation = /** @class */ (function () {
  73279. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  73280. this.name = name;
  73281. this.worldAxisForNormal = worldAxisForNormal;
  73282. this.worldAxisForFileX = worldAxisForFileX;
  73283. this.worldAxisForFileY = worldAxisForFileY;
  73284. }
  73285. return FileFaceOrientation;
  73286. }());
  73287. ;
  73288. /**
  73289. * Helper class dealing with the extraction of spherical polynomial dataArray
  73290. * from a cube map.
  73291. */
  73292. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  73293. function CubeMapToSphericalPolynomialTools() {
  73294. }
  73295. /**
  73296. * Converts a texture to the according Spherical Polynomial data.
  73297. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73298. *
  73299. * @param texture The texture to extract the information from.
  73300. * @return The Spherical Polynomial data.
  73301. */
  73302. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  73303. if (!texture.isCube) {
  73304. // Only supports cube Textures currently.
  73305. return null;
  73306. }
  73307. var size = texture.getSize().width;
  73308. var right = texture.readPixels(0);
  73309. var left = texture.readPixels(1);
  73310. var up;
  73311. var down;
  73312. if (texture.isRenderTarget) {
  73313. up = texture.readPixels(3);
  73314. down = texture.readPixels(2);
  73315. }
  73316. else {
  73317. up = texture.readPixels(2);
  73318. down = texture.readPixels(3);
  73319. }
  73320. var front = texture.readPixels(4);
  73321. var back = texture.readPixels(5);
  73322. var gammaSpace = texture.gammaSpace;
  73323. // Always read as RGBA.
  73324. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  73325. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73326. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73327. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73328. }
  73329. var cubeInfo = {
  73330. size: size,
  73331. right: right,
  73332. left: left,
  73333. up: up,
  73334. down: down,
  73335. front: front,
  73336. back: back,
  73337. format: format,
  73338. type: type,
  73339. gammaSpace: gammaSpace,
  73340. };
  73341. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  73342. };
  73343. /**
  73344. * Converts a cubemap to the according Spherical Polynomial data.
  73345. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73346. *
  73347. * @param cubeInfo The Cube map to extract the information from.
  73348. * @return The Spherical Polynomial data.
  73349. */
  73350. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  73351. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  73352. var totalSolidAngle = 0.0;
  73353. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  73354. var du = 2.0 / cubeInfo.size;
  73355. var dv = du;
  73356. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  73357. var minUV = du * 0.5 - 1.0;
  73358. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73359. var fileFace = this.FileFaces[faceIndex];
  73360. var dataArray = cubeInfo[fileFace.name];
  73361. var v = minUV;
  73362. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  73363. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  73364. // Because SP is still linear, so summation is fine in that basis.
  73365. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  73366. for (var y = 0; y < cubeInfo.size; y++) {
  73367. var u = minUV;
  73368. for (var x = 0; x < cubeInfo.size; x++) {
  73369. // World direction (not normalised)
  73370. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  73371. worldDirection.normalize();
  73372. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  73373. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  73374. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  73375. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  73376. // Handle Integer types.
  73377. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73378. r /= 255;
  73379. g /= 255;
  73380. b /= 255;
  73381. }
  73382. // Handle Gamma space textures.
  73383. if (cubeInfo.gammaSpace) {
  73384. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  73385. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  73386. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  73387. }
  73388. var color = new BABYLON.Color3(r, g, b);
  73389. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  73390. totalSolidAngle += deltaSolidAngle;
  73391. u += du;
  73392. }
  73393. v += dv;
  73394. }
  73395. }
  73396. // Solid angle for entire sphere is 4*pi
  73397. var sphereSolidAngle = 4.0 * Math.PI;
  73398. // Adjust the solid angle to allow for how many faces we processed.
  73399. var facesProcessed = 6.0;
  73400. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  73401. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  73402. // This is needed because the numerical integration over the cube uses a
  73403. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  73404. // and also to compensate for accumulative error due to float precision in the summation.
  73405. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  73406. sphericalHarmonics.scale(correctionFactor);
  73407. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  73408. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  73409. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  73410. };
  73411. CubeMapToSphericalPolynomialTools.FileFaces = [
  73412. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  73413. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  73414. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  73415. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  73416. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  73417. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  73418. ];
  73419. return CubeMapToSphericalPolynomialTools;
  73420. }());
  73421. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  73422. })(BABYLON || (BABYLON = {}));
  73423. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  73424. var BABYLON;
  73425. (function (BABYLON) {
  73426. /**
  73427. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  73428. */
  73429. var PanoramaToCubeMapTools = /** @class */ (function () {
  73430. function PanoramaToCubeMapTools() {
  73431. }
  73432. /**
  73433. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  73434. *
  73435. * @param float32Array The source data.
  73436. * @param inputWidth The width of the input panorama.
  73437. * @param inputhHeight The height of the input panorama.
  73438. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  73439. * @return The cubemap data
  73440. */
  73441. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  73442. if (!float32Array) {
  73443. throw "ConvertPanoramaToCubemap: input cannot be null";
  73444. }
  73445. if (float32Array.length != inputWidth * inputHeight * 3) {
  73446. throw "ConvertPanoramaToCubemap: input size is wrong";
  73447. }
  73448. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  73449. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  73450. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  73451. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  73452. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  73453. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  73454. return {
  73455. front: textureFront,
  73456. back: textureBack,
  73457. left: textureLeft,
  73458. right: textureRight,
  73459. up: textureUp,
  73460. down: textureDown,
  73461. size: size,
  73462. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  73463. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  73464. gammaSpace: false,
  73465. };
  73466. };
  73467. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  73468. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  73469. var textureArray = new Float32Array(buffer);
  73470. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  73471. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  73472. var dy = 1 / texSize;
  73473. var fy = 0;
  73474. for (var y = 0; y < texSize; y++) {
  73475. var xv1 = faceData[0];
  73476. var xv2 = faceData[2];
  73477. for (var x = 0; x < texSize; x++) {
  73478. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  73479. v.normalize();
  73480. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  73481. // 3 channels per pixels
  73482. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  73483. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  73484. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  73485. xv1 = xv1.add(rotDX1);
  73486. xv2 = xv2.add(rotDX2);
  73487. }
  73488. fy += dy;
  73489. }
  73490. return textureArray;
  73491. };
  73492. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  73493. var theta = Math.atan2(vDir.z, vDir.x);
  73494. var phi = Math.acos(vDir.y);
  73495. while (theta < -Math.PI)
  73496. theta += 2 * Math.PI;
  73497. while (theta > Math.PI)
  73498. theta -= 2 * Math.PI;
  73499. var dx = theta / Math.PI;
  73500. var dy = phi / Math.PI;
  73501. // recenter.
  73502. dx = dx * 0.5 + 0.5;
  73503. var px = Math.round(dx * inputWidth);
  73504. if (px < 0)
  73505. px = 0;
  73506. else if (px >= inputWidth)
  73507. px = inputWidth - 1;
  73508. var py = Math.round(dy * inputHeight);
  73509. if (py < 0)
  73510. py = 0;
  73511. else if (py >= inputHeight)
  73512. py = inputHeight - 1;
  73513. var inputY = (inputHeight - py - 1);
  73514. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  73515. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  73516. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  73517. return {
  73518. r: r,
  73519. g: g,
  73520. b: b
  73521. };
  73522. };
  73523. PanoramaToCubeMapTools.FACE_FRONT = [
  73524. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73525. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73526. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73527. new BABYLON.Vector3(1.0, 1.0, -1.0)
  73528. ];
  73529. PanoramaToCubeMapTools.FACE_BACK = [
  73530. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73531. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73532. new BABYLON.Vector3(1.0, 1.0, 1.0),
  73533. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  73534. ];
  73535. PanoramaToCubeMapTools.FACE_RIGHT = [
  73536. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73537. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73538. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73539. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73540. ];
  73541. PanoramaToCubeMapTools.FACE_LEFT = [
  73542. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73543. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73544. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73545. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  73546. ];
  73547. PanoramaToCubeMapTools.FACE_DOWN = [
  73548. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73549. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73550. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73551. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73552. ];
  73553. PanoramaToCubeMapTools.FACE_UP = [
  73554. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73555. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73556. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73557. new BABYLON.Vector3(1.0, -1.0, -1.0)
  73558. ];
  73559. return PanoramaToCubeMapTools;
  73560. }());
  73561. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  73562. })(BABYLON || (BABYLON = {}));
  73563. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  73564. var BABYLON;
  73565. (function (BABYLON) {
  73566. ;
  73567. /**
  73568. * This groups tools to convert HDR texture to native colors array.
  73569. */
  73570. var HDRTools = /** @class */ (function () {
  73571. function HDRTools() {
  73572. }
  73573. HDRTools.Ldexp = function (mantissa, exponent) {
  73574. if (exponent > 1023) {
  73575. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  73576. }
  73577. if (exponent < -1074) {
  73578. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  73579. }
  73580. return mantissa * Math.pow(2, exponent);
  73581. };
  73582. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  73583. if (exponent > 0) {
  73584. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  73585. float32array[index + 0] = red * exponent;
  73586. float32array[index + 1] = green * exponent;
  73587. float32array[index + 2] = blue * exponent;
  73588. }
  73589. else {
  73590. float32array[index + 0] = 0;
  73591. float32array[index + 1] = 0;
  73592. float32array[index + 2] = 0;
  73593. }
  73594. };
  73595. HDRTools.readStringLine = function (uint8array, startIndex) {
  73596. var line = "";
  73597. var character = "";
  73598. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  73599. character = String.fromCharCode(uint8array[i]);
  73600. if (character == "\n") {
  73601. break;
  73602. }
  73603. line += character;
  73604. }
  73605. return line;
  73606. };
  73607. /**
  73608. * Reads header information from an RGBE texture stored in a native array.
  73609. * More information on this format are available here:
  73610. * https://en.wikipedia.org/wiki/RGBE_image_format
  73611. *
  73612. * @param uint8array The binary file stored in native array.
  73613. * @return The header information.
  73614. */
  73615. HDRTools.RGBE_ReadHeader = function (uint8array) {
  73616. var height = 0;
  73617. var width = 0;
  73618. var line = this.readStringLine(uint8array, 0);
  73619. if (line[0] != '#' || line[1] != '?') {
  73620. throw "Bad HDR Format.";
  73621. }
  73622. var endOfHeader = false;
  73623. var findFormat = false;
  73624. var lineIndex = 0;
  73625. do {
  73626. lineIndex += (line.length + 1);
  73627. line = this.readStringLine(uint8array, lineIndex);
  73628. if (line == "FORMAT=32-bit_rle_rgbe") {
  73629. findFormat = true;
  73630. }
  73631. else if (line.length == 0) {
  73632. endOfHeader = true;
  73633. }
  73634. } while (!endOfHeader);
  73635. if (!findFormat) {
  73636. throw "HDR Bad header format, unsupported FORMAT";
  73637. }
  73638. lineIndex += (line.length + 1);
  73639. line = this.readStringLine(uint8array, lineIndex);
  73640. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  73641. var match = sizeRegexp.exec(line);
  73642. // TODO. Support +Y and -X if needed.
  73643. if (!match || match.length < 3) {
  73644. throw "HDR Bad header format, no size";
  73645. }
  73646. width = parseInt(match[2]);
  73647. height = parseInt(match[1]);
  73648. if (width < 8 || width > 0x7fff) {
  73649. throw "HDR Bad header format, unsupported size";
  73650. }
  73651. lineIndex += (line.length + 1);
  73652. return {
  73653. height: height,
  73654. width: width,
  73655. dataPosition: lineIndex
  73656. };
  73657. };
  73658. /**
  73659. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  73660. * This RGBE texture needs to store the information as a panorama.
  73661. *
  73662. * More information on this format are available here:
  73663. * https://en.wikipedia.org/wiki/RGBE_image_format
  73664. *
  73665. * @param buffer The binary file stored in an array buffer.
  73666. * @param size The expected size of the extracted cubemap.
  73667. * @return The Cube Map information.
  73668. */
  73669. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  73670. var uint8array = new Uint8Array(buffer);
  73671. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  73672. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73673. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  73674. return cubeMapData;
  73675. };
  73676. /**
  73677. * Returns the pixels data extracted from an RGBE texture.
  73678. * This pixels will be stored left to right up to down in the R G B order in one array.
  73679. *
  73680. * More information on this format are available here:
  73681. * https://en.wikipedia.org/wiki/RGBE_image_format
  73682. *
  73683. * @param uint8array The binary file stored in an array buffer.
  73684. * @param hdrInfo The header information of the file.
  73685. * @return The pixels data in RGB right to left up to down order.
  73686. */
  73687. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  73688. // Keep for multi format supports.
  73689. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73690. };
  73691. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  73692. var num_scanlines = hdrInfo.height;
  73693. var scanline_width = hdrInfo.width;
  73694. var a, b, c, d, count;
  73695. var dataIndex = hdrInfo.dataPosition;
  73696. var index = 0, endIndex = 0, i = 0;
  73697. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  73698. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  73699. // 3 channels of 4 bytes per pixel in float.
  73700. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  73701. var resultArray = new Float32Array(resultBuffer);
  73702. // read in each successive scanline
  73703. while (num_scanlines > 0) {
  73704. a = uint8array[dataIndex++];
  73705. b = uint8array[dataIndex++];
  73706. c = uint8array[dataIndex++];
  73707. d = uint8array[dataIndex++];
  73708. if (a != 2 || b != 2 || (c & 0x80)) {
  73709. // this file is not run length encoded
  73710. throw "HDR Bad header format, not RLE";
  73711. }
  73712. if (((c << 8) | d) != scanline_width) {
  73713. throw "HDR Bad header format, wrong scan line width";
  73714. }
  73715. index = 0;
  73716. // read each of the four channels for the scanline into the buffer
  73717. for (i = 0; i < 4; i++) {
  73718. endIndex = (i + 1) * scanline_width;
  73719. while (index < endIndex) {
  73720. a = uint8array[dataIndex++];
  73721. b = uint8array[dataIndex++];
  73722. if (a > 128) {
  73723. // a run of the same value
  73724. count = a - 128;
  73725. if ((count == 0) || (count > endIndex - index)) {
  73726. throw "HDR Bad Format, bad scanline data (run)";
  73727. }
  73728. while (count-- > 0) {
  73729. scanLineArray[index++] = b;
  73730. }
  73731. }
  73732. else {
  73733. // a non-run
  73734. count = a;
  73735. if ((count == 0) || (count > endIndex - index)) {
  73736. throw "HDR Bad Format, bad scanline data (non-run)";
  73737. }
  73738. scanLineArray[index++] = b;
  73739. if (--count > 0) {
  73740. for (var j = 0; j < count; j++) {
  73741. scanLineArray[index++] = uint8array[dataIndex++];
  73742. }
  73743. }
  73744. }
  73745. }
  73746. }
  73747. // now convert data from buffer into floats
  73748. for (i = 0; i < scanline_width; i++) {
  73749. a = scanLineArray[i];
  73750. b = scanLineArray[i + scanline_width];
  73751. c = scanLineArray[i + 2 * scanline_width];
  73752. d = scanLineArray[i + 3 * scanline_width];
  73753. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  73754. }
  73755. num_scanlines--;
  73756. }
  73757. return resultArray;
  73758. };
  73759. return HDRTools;
  73760. }());
  73761. BABYLON.HDRTools = HDRTools;
  73762. })(BABYLON || (BABYLON = {}));
  73763. //# sourceMappingURL=babylon.hdr.js.map
  73764. var BABYLON;
  73765. (function (BABYLON) {
  73766. /**
  73767. * This represents a texture coming from an HDR input.
  73768. *
  73769. * The only supported format is currently panorama picture stored in RGBE format.
  73770. * Example of such files can be found on HDRLib: http://hdrlib.com/
  73771. */
  73772. var HDRCubeTexture = /** @class */ (function (_super) {
  73773. __extends(HDRCubeTexture, _super);
  73774. /**
  73775. * Instantiates an HDRTexture from the following parameters.
  73776. *
  73777. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  73778. * @param scene The scene the texture will be used in
  73779. * @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.
  73780. * @param noMipmap Forces to not generate the mipmap if true
  73781. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  73782. * @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)
  73783. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  73784. */
  73785. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  73786. if (noMipmap === void 0) { noMipmap = false; }
  73787. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73788. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73789. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73790. if (onLoad === void 0) { onLoad = null; }
  73791. if (onError === void 0) { onError = null; }
  73792. var _this = _super.call(this, scene) || this;
  73793. _this._useInGammaSpace = false;
  73794. _this._generateHarmonics = true;
  73795. _this._isBABYLONPreprocessed = false;
  73796. _this._onLoad = null;
  73797. _this._onError = null;
  73798. /**
  73799. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  73800. */
  73801. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  73802. /**
  73803. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  73804. * This is usefull at run time to apply the good shader.
  73805. */
  73806. _this.isPMREM = false;
  73807. _this._isBlocking = true;
  73808. /**
  73809. * Gets or sets the center of the bounding box associated with the cube texture
  73810. * It must define where the camera used to render the texture was set
  73811. */
  73812. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73813. if (!url) {
  73814. return _this;
  73815. }
  73816. _this.name = url;
  73817. _this.url = url;
  73818. _this.hasAlpha = false;
  73819. _this.isCube = true;
  73820. _this._textureMatrix = BABYLON.Matrix.Identity();
  73821. _this._onLoad = onLoad;
  73822. _this._onError = onError;
  73823. _this.gammaSpace = false;
  73824. var caps = scene.getEngine().getCaps();
  73825. if (size) {
  73826. _this._isBABYLONPreprocessed = false;
  73827. _this._noMipmap = noMipmap;
  73828. _this._size = size;
  73829. _this._useInGammaSpace = useInGammaSpace;
  73830. _this._usePMREMGenerator = usePMREMGenerator &&
  73831. caps.textureLOD &&
  73832. caps.textureFloat &&
  73833. !_this._useInGammaSpace;
  73834. }
  73835. else {
  73836. _this._isBABYLONPreprocessed = true;
  73837. _this._noMipmap = false;
  73838. _this._useInGammaSpace = false;
  73839. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  73840. !_this._useInGammaSpace;
  73841. }
  73842. _this.isPMREM = _this._usePMREMGenerator;
  73843. _this._texture = _this._getFromCache(url, _this._noMipmap);
  73844. if (!_this._texture) {
  73845. if (!scene.useDelayedTextureLoading) {
  73846. _this.loadTexture();
  73847. }
  73848. else {
  73849. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  73850. }
  73851. }
  73852. return _this;
  73853. }
  73854. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  73855. /**
  73856. * Gets wether or not the texture is blocking during loading.
  73857. */
  73858. get: function () {
  73859. return this._isBlocking;
  73860. },
  73861. /**
  73862. * Sets wether or not the texture is blocking during loading.
  73863. */
  73864. set: function (value) {
  73865. this._isBlocking = value;
  73866. },
  73867. enumerable: true,
  73868. configurable: true
  73869. });
  73870. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  73871. get: function () {
  73872. return this._boundingBoxSize;
  73873. },
  73874. /**
  73875. * Gets or sets the size of the bounding box associated with the cube texture
  73876. * When defined, the cubemap will switch to local mode
  73877. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73878. * @example https://www.babylonjs-playground.com/#RNASML
  73879. */
  73880. set: function (value) {
  73881. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73882. return;
  73883. }
  73884. this._boundingBoxSize = value;
  73885. var scene = this.getScene();
  73886. if (scene) {
  73887. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73888. }
  73889. },
  73890. enumerable: true,
  73891. configurable: true
  73892. });
  73893. /**
  73894. * Occurs when the file is a preprocessed .babylon.hdr file.
  73895. */
  73896. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  73897. var _this = this;
  73898. var mipLevels = 0;
  73899. var floatArrayView = null;
  73900. var scene = this.getScene();
  73901. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  73902. var mips = new Array();
  73903. if (!floatArrayView) {
  73904. return mips;
  73905. }
  73906. var startIndex = 30;
  73907. for (var level = 0; level < mipLevels; level++) {
  73908. mips.push([]);
  73909. // Fill each pixel of the mip level.
  73910. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  73911. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73912. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  73913. mips[level].push(faceData);
  73914. startIndex += faceSize;
  73915. }
  73916. }
  73917. return mips;
  73918. } : null;
  73919. var callback = function (buffer) {
  73920. var scene = _this.getScene();
  73921. if (!scene) {
  73922. return null;
  73923. }
  73924. // Create Native Array Views
  73925. var intArrayView = new Int32Array(buffer);
  73926. floatArrayView = new Float32Array(buffer);
  73927. // Fill header.
  73928. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  73929. _this._size = intArrayView[1]; // CubeMap max mip face size.
  73930. // Update Texture Information.
  73931. if (!_this._texture) {
  73932. return null;
  73933. }
  73934. _this._texture.updateSize(_this._size, _this._size);
  73935. // Fill polynomial information.
  73936. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  73937. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  73938. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  73939. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  73940. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  73941. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  73942. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  73943. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  73944. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  73945. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  73946. _this.sphericalPolynomial = sphericalPolynomial;
  73947. // Fill pixel data.
  73948. mipLevels = intArrayView[29]; // Number of mip levels.
  73949. var startIndex = 30;
  73950. var data = [];
  73951. var faceSize = Math.pow(_this._size, 2) * 3;
  73952. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73953. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  73954. startIndex += faceSize;
  73955. }
  73956. var results = [];
  73957. var byteArray = null;
  73958. // Push each faces.
  73959. for (var k = 0; k < 6; k++) {
  73960. var dataFace = null;
  73961. // To be deprecated.
  73962. if (version === 1) {
  73963. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  73964. dataFace = data[j];
  73965. }
  73966. // If special cases.
  73967. if (!mipmapGenerator && dataFace) {
  73968. if (!scene.getEngine().getCaps().textureFloat) {
  73969. // 3 channels of 1 bytes per pixel in bytes.
  73970. var byteBuffer = new ArrayBuffer(faceSize);
  73971. byteArray = new Uint8Array(byteBuffer);
  73972. }
  73973. for (var i = 0; i < _this._size * _this._size; i++) {
  73974. // Put in gamma space if requested.
  73975. if (_this._useInGammaSpace) {
  73976. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73977. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73978. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73979. }
  73980. // Convert to int texture for fallback.
  73981. if (byteArray) {
  73982. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73983. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73984. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73985. // May use luminance instead if the result is not accurate.
  73986. var max = Math.max(Math.max(r, g), b);
  73987. if (max > 255) {
  73988. var scale = 255 / max;
  73989. r *= scale;
  73990. g *= scale;
  73991. b *= scale;
  73992. }
  73993. byteArray[(i * 3) + 0] = r;
  73994. byteArray[(i * 3) + 1] = g;
  73995. byteArray[(i * 3) + 2] = b;
  73996. }
  73997. }
  73998. }
  73999. // Fill the array accordingly.
  74000. if (byteArray) {
  74001. results.push(byteArray);
  74002. }
  74003. else {
  74004. results.push(dataFace);
  74005. }
  74006. }
  74007. return results;
  74008. };
  74009. if (scene) {
  74010. 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);
  74011. }
  74012. };
  74013. /**
  74014. * Occurs when the file is raw .hdr file.
  74015. */
  74016. HDRCubeTexture.prototype.loadHDRTexture = function () {
  74017. var _this = this;
  74018. var callback = function (buffer) {
  74019. var scene = _this.getScene();
  74020. if (!scene) {
  74021. return null;
  74022. }
  74023. // Extract the raw linear data.
  74024. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  74025. // Generate harmonics if needed.
  74026. if (_this._generateHarmonics) {
  74027. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  74028. _this.sphericalPolynomial = sphericalPolynomial;
  74029. }
  74030. var results = [];
  74031. var byteArray = null;
  74032. // Push each faces.
  74033. for (var j = 0; j < 6; j++) {
  74034. // Create uintarray fallback.
  74035. if (!scene.getEngine().getCaps().textureFloat) {
  74036. // 3 channels of 1 bytes per pixel in bytes.
  74037. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  74038. byteArray = new Uint8Array(byteBuffer);
  74039. }
  74040. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  74041. // If special cases.
  74042. if (_this._useInGammaSpace || byteArray) {
  74043. for (var i = 0; i < _this._size * _this._size; i++) {
  74044. // Put in gamma space if requested.
  74045. if (_this._useInGammaSpace) {
  74046. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74047. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74048. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74049. }
  74050. // Convert to int texture for fallback.
  74051. if (byteArray) {
  74052. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74053. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74054. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74055. // May use luminance instead if the result is not accurate.
  74056. var max = Math.max(Math.max(r, g), b);
  74057. if (max > 255) {
  74058. var scale = 255 / max;
  74059. r *= scale;
  74060. g *= scale;
  74061. b *= scale;
  74062. }
  74063. byteArray[(i * 3) + 0] = r;
  74064. byteArray[(i * 3) + 1] = g;
  74065. byteArray[(i * 3) + 2] = b;
  74066. }
  74067. }
  74068. }
  74069. if (byteArray) {
  74070. results.push(byteArray);
  74071. }
  74072. else {
  74073. results.push(dataFace);
  74074. }
  74075. }
  74076. return results;
  74077. };
  74078. var mipmapGenerator = null;
  74079. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  74080. // if (!this._noMipmap &&
  74081. // this._usePMREMGenerator) {
  74082. // mipmapGenerator = (data: ArrayBufferView[]) => {
  74083. // // Custom setup of the generator matching with the PBR shader values.
  74084. // var generator = new BABYLON.PMREMGenerator(data,
  74085. // this._size,
  74086. // this._size,
  74087. // 0,
  74088. // 3,
  74089. // this.getScene().getEngine().getCaps().textureFloat,
  74090. // 2048,
  74091. // 0.25,
  74092. // false,
  74093. // true);
  74094. // return generator.filterCubeMap();
  74095. // };
  74096. // }
  74097. var scene = this.getScene();
  74098. if (scene) {
  74099. 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);
  74100. }
  74101. };
  74102. /**
  74103. * Starts the loading process of the texture.
  74104. */
  74105. HDRCubeTexture.prototype.loadTexture = function () {
  74106. if (this._isBABYLONPreprocessed) {
  74107. this.loadBabylonTexture();
  74108. }
  74109. else {
  74110. this.loadHDRTexture();
  74111. }
  74112. };
  74113. HDRCubeTexture.prototype.clone = function () {
  74114. var scene = this.getScene();
  74115. if (!scene) {
  74116. return this;
  74117. }
  74118. var size = (this._isBABYLONPreprocessed ? null : this._size);
  74119. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  74120. // Base texture
  74121. newTexture.level = this.level;
  74122. newTexture.wrapU = this.wrapU;
  74123. newTexture.wrapV = this.wrapV;
  74124. newTexture.coordinatesIndex = this.coordinatesIndex;
  74125. newTexture.coordinatesMode = this.coordinatesMode;
  74126. return newTexture;
  74127. };
  74128. // Methods
  74129. HDRCubeTexture.prototype.delayLoad = function () {
  74130. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  74131. return;
  74132. }
  74133. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  74134. this._texture = this._getFromCache(this.url, this._noMipmap);
  74135. if (!this._texture) {
  74136. this.loadTexture();
  74137. }
  74138. };
  74139. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  74140. return this._textureMatrix;
  74141. };
  74142. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  74143. this._textureMatrix = value;
  74144. };
  74145. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  74146. var texture = null;
  74147. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  74148. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  74149. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  74150. texture.name = parsedTexture.name;
  74151. texture.hasAlpha = parsedTexture.hasAlpha;
  74152. texture.level = parsedTexture.level;
  74153. texture.coordinatesMode = parsedTexture.coordinatesMode;
  74154. texture.isBlocking = parsedTexture.isBlocking;
  74155. }
  74156. if (texture) {
  74157. if (parsedTexture.boundingBoxPosition) {
  74158. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  74159. }
  74160. if (parsedTexture.boundingBoxSize) {
  74161. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  74162. }
  74163. }
  74164. return texture;
  74165. };
  74166. HDRCubeTexture.prototype.serialize = function () {
  74167. if (!this.name) {
  74168. return null;
  74169. }
  74170. var serializationObject = {};
  74171. serializationObject.name = this.name;
  74172. serializationObject.hasAlpha = this.hasAlpha;
  74173. serializationObject.isCube = true;
  74174. serializationObject.level = this.level;
  74175. serializationObject.size = this._size;
  74176. serializationObject.coordinatesMode = this.coordinatesMode;
  74177. serializationObject.useInGammaSpace = this._useInGammaSpace;
  74178. serializationObject.generateHarmonics = this._generateHarmonics;
  74179. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  74180. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  74181. serializationObject.customType = "BABYLON.HDRCubeTexture";
  74182. serializationObject.noMipmap = this._noMipmap;
  74183. serializationObject.isBlocking = this._isBlocking;
  74184. return serializationObject;
  74185. };
  74186. /**
  74187. * Saves as a file the data contained in the texture in a binary format.
  74188. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74189. * as the spherical used in the lighting.
  74190. * @param url The HDR file url.
  74191. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74192. * @param onError Method called if any error happens during download.
  74193. * @return The packed binary data.
  74194. */
  74195. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  74196. if (onError === void 0) { onError = null; }
  74197. var callback = function (buffer) {
  74198. var data = new Blob([buffer], { type: 'application/octet-stream' });
  74199. // Returns a URL you can use as a href.
  74200. var objUrl = window.URL.createObjectURL(data);
  74201. // Simulates a link to it and click to dowload.
  74202. var a = document.createElement("a");
  74203. document.body.appendChild(a);
  74204. a.style.display = "none";
  74205. a.href = objUrl;
  74206. a.download = "envmap.babylon.hdr";
  74207. a.click();
  74208. };
  74209. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  74210. };
  74211. /**
  74212. * Serializes the data contained in the texture in a binary format.
  74213. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74214. * as the spherical used in the lighting.
  74215. * @param url The HDR file url.
  74216. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74217. * @param onError Method called if any error happens during download.
  74218. * @return The packed binary data.
  74219. */
  74220. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  74221. if (onError === void 0) { onError = null; }
  74222. // Needs the url tho create the texture.
  74223. if (!url) {
  74224. return;
  74225. }
  74226. // Check Power of two size.
  74227. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  74228. return;
  74229. }
  74230. // Coming Back in 3.x.
  74231. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  74232. };
  74233. HDRCubeTexture._facesMapping = [
  74234. "right",
  74235. "left",
  74236. "up",
  74237. "down",
  74238. "front",
  74239. "back"
  74240. ];
  74241. return HDRCubeTexture;
  74242. }(BABYLON.BaseTexture));
  74243. BABYLON.HDRCubeTexture = HDRCubeTexture;
  74244. })(BABYLON || (BABYLON = {}));
  74245. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  74246. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  74247. // Huge respect for a such great lib.
  74248. // Earcut license:
  74249. // Copyright (c) 2016, Mapbox
  74250. //
  74251. // Permission to use, copy, modify, and/or distribute this software for any purpose
  74252. // with or without fee is hereby granted, provided that the above copyright notice
  74253. // and this permission notice appear in all copies.
  74254. //
  74255. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  74256. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  74257. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  74258. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  74259. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  74260. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  74261. // THIS SOFTWARE.
  74262. var Earcut;
  74263. (function (Earcut) {
  74264. /**
  74265. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  74266. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  74267. * @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).
  74268. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  74269. */
  74270. function earcut(data, holeIndices, dim) {
  74271. dim = dim || 2;
  74272. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  74273. if (!outerNode)
  74274. return triangles;
  74275. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  74276. if (hasHoles)
  74277. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  74278. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  74279. if (data.length > 80 * dim) {
  74280. minX = maxX = data[0];
  74281. minY = maxY = data[1];
  74282. for (var i = dim; i < outerLen; i += dim) {
  74283. x = data[i];
  74284. y = data[i + 1];
  74285. if (x < minX)
  74286. minX = x;
  74287. if (y < minY)
  74288. minY = y;
  74289. if (x > maxX)
  74290. maxX = x;
  74291. if (y > maxY)
  74292. maxY = y;
  74293. }
  74294. // minX, minY and size are later used to transform coords into integers for z-order calculation
  74295. size = Math.max(maxX - minX, maxY - minY);
  74296. }
  74297. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  74298. return triangles;
  74299. }
  74300. Earcut.earcut = earcut;
  74301. var Node = /** @class */ (function () {
  74302. function Node(i, x, y) {
  74303. this.i = i;
  74304. this.x = x;
  74305. this.y = y;
  74306. this.prev = null;
  74307. this.next = null;
  74308. this.z = null;
  74309. this.prevZ = null;
  74310. this.nextZ = null;
  74311. this.steiner = false;
  74312. }
  74313. return Node;
  74314. }());
  74315. // create a circular doubly linked list from polygon points in the specified winding order
  74316. function linkedList(data, start, end, dim, clockwise) {
  74317. var i, last = null;
  74318. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  74319. for (i = start; i < end; i += dim)
  74320. last = insertNode(i, data[i], data[i + 1], last);
  74321. }
  74322. else {
  74323. for (i = end - dim; i >= start; i -= dim)
  74324. last = insertNode(i, data[i], data[i + 1], last);
  74325. }
  74326. if (last && equals(last, last.next)) {
  74327. removeNode(last);
  74328. last = last.next;
  74329. }
  74330. return last;
  74331. }
  74332. // eliminate colinear or duplicate points
  74333. function filterPoints(start, end) {
  74334. if (!start)
  74335. return start;
  74336. if (!end)
  74337. end = start;
  74338. var p = start, again;
  74339. do {
  74340. again = false;
  74341. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  74342. removeNode(p);
  74343. p = end = p.prev;
  74344. if (p === p.next)
  74345. return undefined;
  74346. again = true;
  74347. }
  74348. else {
  74349. p = p.next;
  74350. }
  74351. } while (again || p !== end);
  74352. return end;
  74353. }
  74354. // main ear slicing loop which triangulates a polygon (given as a linked list)
  74355. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  74356. if (!ear)
  74357. return;
  74358. // interlink polygon nodes in z-order
  74359. if (!pass && size)
  74360. indexCurve(ear, minX, minY, size);
  74361. var stop = ear, prev, next;
  74362. // iterate through ears, slicing them one by one
  74363. while (ear.prev !== ear.next) {
  74364. prev = ear.prev;
  74365. next = ear.next;
  74366. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  74367. // cut off the triangle
  74368. triangles.push(prev.i / dim);
  74369. triangles.push(ear.i / dim);
  74370. triangles.push(next.i / dim);
  74371. removeNode(ear);
  74372. // skipping the next vertice leads to less sliver triangles
  74373. ear = next.next;
  74374. stop = next.next;
  74375. continue;
  74376. }
  74377. ear = next;
  74378. // if we looped through the whole remaining polygon and can't find any more ears
  74379. if (ear === stop) {
  74380. // try filtering points and slicing again
  74381. if (!pass) {
  74382. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  74383. // if this didn't work, try curing all small self-intersections locally
  74384. }
  74385. else if (pass === 1) {
  74386. ear = cureLocalIntersections(ear, triangles, dim);
  74387. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  74388. // as a last resort, try splitting the remaining polygon into two
  74389. }
  74390. else if (pass === 2) {
  74391. splitEarcut(ear, triangles, dim, minX, minY, size);
  74392. }
  74393. break;
  74394. }
  74395. }
  74396. }
  74397. // check whether a polygon node forms a valid ear with adjacent nodes
  74398. function isEar(ear) {
  74399. var a = ear.prev, b = ear, c = ear.next;
  74400. if (area(a, b, c) >= 0)
  74401. return false; // reflex, can't be an ear
  74402. // now make sure we don't have other points inside the potential ear
  74403. var p = ear.next.next;
  74404. while (p !== ear.prev) {
  74405. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74406. area(p.prev, p, p.next) >= 0)
  74407. return false;
  74408. p = p.next;
  74409. }
  74410. return true;
  74411. }
  74412. function isEarHashed(ear, minX, minY, size) {
  74413. var a = ear.prev, b = ear, c = ear.next;
  74414. if (area(a, b, c) >= 0)
  74415. return false; // reflex, can't be an ear
  74416. // triangle bbox; min & max are calculated like this for speed
  74417. 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);
  74418. // z-order range for the current triangle bbox;
  74419. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  74420. // first look for points inside the triangle in increasing z-order
  74421. var p = ear.nextZ;
  74422. while (p && p.z <= maxZ) {
  74423. if (p !== ear.prev &&
  74424. p !== ear.next &&
  74425. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74426. area(p.prev, p, p.next) >= 0)
  74427. return false;
  74428. p = p.nextZ;
  74429. }
  74430. // then look for points in decreasing z-order
  74431. p = ear.prevZ;
  74432. while (p && p.z >= minZ) {
  74433. if (p !== ear.prev &&
  74434. p !== ear.next &&
  74435. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74436. area(p.prev, p, p.next) >= 0)
  74437. return false;
  74438. p = p.prevZ;
  74439. }
  74440. return true;
  74441. }
  74442. // go through all polygon nodes and cure small local self-intersections
  74443. function cureLocalIntersections(start, triangles, dim) {
  74444. var p = start;
  74445. do {
  74446. var a = p.prev, b = p.next.next;
  74447. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  74448. triangles.push(a.i / dim);
  74449. triangles.push(p.i / dim);
  74450. triangles.push(b.i / dim);
  74451. // remove two nodes involved
  74452. removeNode(p);
  74453. removeNode(p.next);
  74454. p = start = b;
  74455. }
  74456. p = p.next;
  74457. } while (p !== start);
  74458. return p;
  74459. }
  74460. // try splitting polygon into two and triangulate them independently
  74461. function splitEarcut(start, triangles, dim, minX, minY, size) {
  74462. // look for a valid diagonal that divides the polygon into two
  74463. var a = start;
  74464. do {
  74465. var b = a.next.next;
  74466. while (b !== a.prev) {
  74467. if (a.i !== b.i && isValidDiagonal(a, b)) {
  74468. // split the polygon in two by the diagonal
  74469. var c = splitPolygon(a, b);
  74470. // filter colinear points around the cuts
  74471. a = filterPoints(a, a.next);
  74472. c = filterPoints(c, c.next);
  74473. // run earcut on each half
  74474. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  74475. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  74476. return;
  74477. }
  74478. b = b.next;
  74479. }
  74480. a = a.next;
  74481. } while (a !== start);
  74482. }
  74483. // link every hole into the outer loop, producing a single-ring polygon without holes
  74484. function eliminateHoles(data, holeIndices, outerNode, dim) {
  74485. var queue = [], i, len, start, end, list;
  74486. for (i = 0, len = holeIndices.length; i < len; i++) {
  74487. start = holeIndices[i] * dim;
  74488. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74489. list = linkedList(data, start, end, dim, false);
  74490. if (list === list.next)
  74491. list.steiner = true;
  74492. queue.push(getLeftmost(list));
  74493. }
  74494. queue.sort(compareX);
  74495. // process holes from left to right
  74496. for (i = 0; i < queue.length; i++) {
  74497. eliminateHole(queue[i], outerNode);
  74498. outerNode = filterPoints(outerNode, outerNode.next);
  74499. }
  74500. return outerNode;
  74501. }
  74502. function compareX(a, b) {
  74503. return a.x - b.x;
  74504. }
  74505. // find a bridge between vertices that connects hole with an outer ring and and link it
  74506. function eliminateHole(hole, outerNode) {
  74507. outerNode = findHoleBridge(hole, outerNode);
  74508. if (outerNode) {
  74509. var b = splitPolygon(outerNode, hole);
  74510. filterPoints(b, b.next);
  74511. }
  74512. }
  74513. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  74514. function findHoleBridge(hole, outerNode) {
  74515. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  74516. // find a segment intersected by a ray from the hole's leftmost point to the left;
  74517. // segment's endpoint with lesser x will be potential connection point
  74518. do {
  74519. if (hy <= p.y && hy >= p.next.y) {
  74520. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  74521. if (x <= hx && x > qx) {
  74522. qx = x;
  74523. if (x === hx) {
  74524. if (hy === p.y)
  74525. return p;
  74526. if (hy === p.next.y)
  74527. return p.next;
  74528. }
  74529. m = p.x < p.next.x ? p : p.next;
  74530. }
  74531. }
  74532. p = p.next;
  74533. } while (p !== outerNode);
  74534. if (!m)
  74535. return null;
  74536. if (hx === qx)
  74537. return m.prev; // hole touches outer segment; pick lower endpoint
  74538. // look for points inside the triangle of hole point, segment intersection and endpoint;
  74539. // if there are no points found, we have a valid connection;
  74540. // otherwise choose the point of the minimum angle with the ray as connection point
  74541. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  74542. p = m.next;
  74543. while (p !== stop) {
  74544. if (hx >= p.x &&
  74545. p.x >= mx &&
  74546. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  74547. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  74548. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  74549. m = p;
  74550. tanMin = tan;
  74551. }
  74552. }
  74553. p = p.next;
  74554. }
  74555. return m;
  74556. }
  74557. // interlink polygon nodes in z-order
  74558. function indexCurve(start, minX, minY, size) {
  74559. var p = start;
  74560. do {
  74561. if (p.z === null)
  74562. p.z = zOrder(p.x, p.y, minX, minY, size);
  74563. p.prevZ = p.prev;
  74564. p.nextZ = p.next;
  74565. p = p.next;
  74566. } while (p !== start);
  74567. p.prevZ.nextZ = null;
  74568. p.prevZ = null;
  74569. sortLinked(p);
  74570. }
  74571. // Simon Tatham's linked list merge sort algorithm
  74572. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  74573. function sortLinked(list) {
  74574. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  74575. do {
  74576. p = list;
  74577. list = null;
  74578. tail = null;
  74579. numMerges = 0;
  74580. while (p) {
  74581. numMerges++;
  74582. q = p;
  74583. pSize = 0;
  74584. for (i = 0; i < inSize; i++) {
  74585. pSize++;
  74586. q = q.nextZ;
  74587. if (!q)
  74588. break;
  74589. }
  74590. qSize = inSize;
  74591. while (pSize > 0 || (qSize > 0 && q)) {
  74592. if (pSize === 0) {
  74593. e = q;
  74594. q = q.nextZ;
  74595. qSize--;
  74596. }
  74597. else if (qSize === 0 || !q) {
  74598. e = p;
  74599. p = p.nextZ;
  74600. pSize--;
  74601. }
  74602. else if (p.z <= q.z) {
  74603. e = p;
  74604. p = p.nextZ;
  74605. pSize--;
  74606. }
  74607. else {
  74608. e = q;
  74609. q = q.nextZ;
  74610. qSize--;
  74611. }
  74612. if (tail)
  74613. tail.nextZ = e;
  74614. else
  74615. list = e;
  74616. e.prevZ = tail;
  74617. tail = e;
  74618. }
  74619. p = q;
  74620. }
  74621. tail.nextZ = null;
  74622. inSize *= 2;
  74623. } while (numMerges > 1);
  74624. return list;
  74625. }
  74626. // z-order of a point given coords and size of the data bounding box
  74627. function zOrder(x, y, minX, minY, size) {
  74628. // coords are transformed into non-negative 15-bit integer range
  74629. x = 32767 * (x - minX) / size;
  74630. y = 32767 * (y - minY) / size;
  74631. x = (x | (x << 8)) & 0x00FF00FF;
  74632. x = (x | (x << 4)) & 0x0F0F0F0F;
  74633. x = (x | (x << 2)) & 0x33333333;
  74634. x = (x | (x << 1)) & 0x55555555;
  74635. y = (y | (y << 8)) & 0x00FF00FF;
  74636. y = (y | (y << 4)) & 0x0F0F0F0F;
  74637. y = (y | (y << 2)) & 0x33333333;
  74638. y = (y | (y << 1)) & 0x55555555;
  74639. return x | (y << 1);
  74640. }
  74641. // find the leftmost node of a polygon ring
  74642. function getLeftmost(start) {
  74643. var p = start, leftmost = start;
  74644. do {
  74645. if (p.x < leftmost.x)
  74646. leftmost = p;
  74647. p = p.next;
  74648. } while (p !== start);
  74649. return leftmost;
  74650. }
  74651. // check if a point lies within a convex triangle
  74652. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  74653. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  74654. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  74655. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  74656. }
  74657. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  74658. function isValidDiagonal(a, b) {
  74659. return a.next.i !== b.i &&
  74660. a.prev.i !== b.i &&
  74661. !intersectsPolygon(a, b) &&
  74662. locallyInside(a, b) &&
  74663. locallyInside(b, a) &&
  74664. middleInside(a, b);
  74665. }
  74666. // signed area of a triangle
  74667. function area(p, q, r) {
  74668. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  74669. }
  74670. // check if two points are equal
  74671. function equals(p1, p2) {
  74672. return p1.x === p2.x && p1.y === p2.y;
  74673. }
  74674. // check if two segments intersect
  74675. function intersects(p1, q1, p2, q2) {
  74676. if ((equals(p1, q1) && equals(p2, q2)) ||
  74677. (equals(p1, q2) && equals(p2, q1)))
  74678. return true;
  74679. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  74680. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  74681. }
  74682. // check if a polygon diagonal intersects any polygon segments
  74683. function intersectsPolygon(a, b) {
  74684. var p = a;
  74685. do {
  74686. if (p.i !== a.i &&
  74687. p.next.i !== a.i &&
  74688. p.i !== b.i &&
  74689. p.next.i !== b.i &&
  74690. intersects(p, p.next, a, b))
  74691. return true;
  74692. p = p.next;
  74693. } while (p !== a);
  74694. return false;
  74695. }
  74696. // check if a polygon diagonal is locally inside the polygon
  74697. function locallyInside(a, b) {
  74698. return area(a.prev, a, a.next) < 0
  74699. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  74700. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  74701. }
  74702. // check if the middle point of a polygon diagonal is inside the polygon
  74703. function middleInside(a, b) {
  74704. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  74705. do {
  74706. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  74707. inside = !inside;
  74708. p = p.next;
  74709. } while (p !== a);
  74710. return inside;
  74711. }
  74712. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  74713. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  74714. function splitPolygon(a, b) {
  74715. 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;
  74716. a.next = b;
  74717. b.prev = a;
  74718. a2.next = an;
  74719. an.prev = a2;
  74720. b2.next = a2;
  74721. a2.prev = b2;
  74722. bp.next = b2;
  74723. b2.prev = bp;
  74724. return b2;
  74725. }
  74726. // create a node and optionally link it with previous one (in a circular doubly linked list)
  74727. function insertNode(i, x, y, last) {
  74728. var p = new Node(i, x, y);
  74729. if (!last) {
  74730. p.prev = p;
  74731. p.next = p;
  74732. }
  74733. else {
  74734. p.next = last.next;
  74735. p.prev = last;
  74736. last.next.prev = p;
  74737. last.next = p;
  74738. }
  74739. return p;
  74740. }
  74741. function removeNode(p) {
  74742. p.next.prev = p.prev;
  74743. p.prev.next = p.next;
  74744. if (p.prevZ)
  74745. p.prevZ.nextZ = p.nextZ;
  74746. if (p.nextZ)
  74747. p.nextZ.prevZ = p.prevZ;
  74748. }
  74749. /**
  74750. * return a percentage difference between the polygon area and its triangulation area;
  74751. * used to verify correctness of triangulation
  74752. */
  74753. function deviation(data, holeIndices, dim, triangles) {
  74754. var hasHoles = holeIndices && holeIndices.length;
  74755. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  74756. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  74757. if (hasHoles) {
  74758. for (var i = 0, len = holeIndices.length; i < len; i++) {
  74759. var start = holeIndices[i] * dim;
  74760. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74761. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  74762. }
  74763. }
  74764. var trianglesArea = 0;
  74765. for (i = 0; i < triangles.length; i += 3) {
  74766. var a = triangles[i] * dim;
  74767. var b = triangles[i + 1] * dim;
  74768. var c = triangles[i + 2] * dim;
  74769. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  74770. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  74771. }
  74772. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  74773. }
  74774. Earcut.deviation = deviation;
  74775. ;
  74776. function signedArea(data, start, end, dim) {
  74777. var sum = 0;
  74778. for (var i = start, j = end - dim; i < end; i += dim) {
  74779. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  74780. j = i;
  74781. }
  74782. return sum;
  74783. }
  74784. /**
  74785. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  74786. */
  74787. function flatten(data) {
  74788. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  74789. for (var i = 0; i < data.length; i++) {
  74790. for (var j = 0; j < data[i].length; j++) {
  74791. for (var d = 0; d < dim; d++)
  74792. result.vertices.push(data[i][j][d]);
  74793. }
  74794. if (i > 0) {
  74795. holeIndex += data[i - 1].length;
  74796. result.holes.push(holeIndex);
  74797. }
  74798. }
  74799. return result;
  74800. }
  74801. Earcut.flatten = flatten;
  74802. ;
  74803. })(Earcut || (Earcut = {}));
  74804. //# sourceMappingURL=babylon.earcut.js.map
  74805. var BABYLON;
  74806. (function (BABYLON) {
  74807. var IndexedVector2 = /** @class */ (function (_super) {
  74808. __extends(IndexedVector2, _super);
  74809. function IndexedVector2(original, index) {
  74810. var _this = _super.call(this, original.x, original.y) || this;
  74811. _this.index = index;
  74812. return _this;
  74813. }
  74814. return IndexedVector2;
  74815. }(BABYLON.Vector2));
  74816. var PolygonPoints = /** @class */ (function () {
  74817. function PolygonPoints() {
  74818. this.elements = new Array();
  74819. }
  74820. PolygonPoints.prototype.add = function (originalPoints) {
  74821. var _this = this;
  74822. var result = new Array();
  74823. originalPoints.forEach(function (point) {
  74824. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  74825. var newPoint = new IndexedVector2(point, _this.elements.length);
  74826. result.push(newPoint);
  74827. _this.elements.push(newPoint);
  74828. }
  74829. });
  74830. return result;
  74831. };
  74832. PolygonPoints.prototype.computeBounds = function () {
  74833. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74834. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74835. this.elements.forEach(function (point) {
  74836. // x
  74837. if (point.x < lmin.x) {
  74838. lmin.x = point.x;
  74839. }
  74840. else if (point.x > lmax.x) {
  74841. lmax.x = point.x;
  74842. }
  74843. // y
  74844. if (point.y < lmin.y) {
  74845. lmin.y = point.y;
  74846. }
  74847. else if (point.y > lmax.y) {
  74848. lmax.y = point.y;
  74849. }
  74850. });
  74851. return {
  74852. min: lmin,
  74853. max: lmax,
  74854. width: lmax.x - lmin.x,
  74855. height: lmax.y - lmin.y
  74856. };
  74857. };
  74858. return PolygonPoints;
  74859. }());
  74860. var Polygon = /** @class */ (function () {
  74861. function Polygon() {
  74862. }
  74863. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  74864. return [
  74865. new BABYLON.Vector2(xmin, ymin),
  74866. new BABYLON.Vector2(xmax, ymin),
  74867. new BABYLON.Vector2(xmax, ymax),
  74868. new BABYLON.Vector2(xmin, ymax)
  74869. ];
  74870. };
  74871. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  74872. if (cx === void 0) { cx = 0; }
  74873. if (cy === void 0) { cy = 0; }
  74874. if (numberOfSides === void 0) { numberOfSides = 32; }
  74875. var result = new Array();
  74876. var angle = 0;
  74877. var increment = (Math.PI * 2) / numberOfSides;
  74878. for (var i = 0; i < numberOfSides; i++) {
  74879. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  74880. angle -= increment;
  74881. }
  74882. return result;
  74883. };
  74884. Polygon.Parse = function (input) {
  74885. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  74886. var i, result = [];
  74887. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  74888. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  74889. }
  74890. return result;
  74891. };
  74892. Polygon.StartingAt = function (x, y) {
  74893. return BABYLON.Path2.StartingAt(x, y);
  74894. };
  74895. return Polygon;
  74896. }());
  74897. BABYLON.Polygon = Polygon;
  74898. var PolygonMeshBuilder = /** @class */ (function () {
  74899. function PolygonMeshBuilder(name, contours, scene) {
  74900. this._points = new PolygonPoints();
  74901. this._outlinepoints = new PolygonPoints();
  74902. this._holes = new Array();
  74903. this._epoints = new Array();
  74904. this._eholes = new Array();
  74905. this._name = name;
  74906. this._scene = scene;
  74907. var points;
  74908. if (contours instanceof BABYLON.Path2) {
  74909. points = contours.getPoints();
  74910. }
  74911. else {
  74912. points = contours;
  74913. }
  74914. this._addToepoint(points);
  74915. this._points.add(points);
  74916. this._outlinepoints.add(points);
  74917. }
  74918. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  74919. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  74920. var p = points_1[_i];
  74921. this._epoints.push(p.x, p.y);
  74922. }
  74923. };
  74924. PolygonMeshBuilder.prototype.addHole = function (hole) {
  74925. this._points.add(hole);
  74926. var holepoints = new PolygonPoints();
  74927. holepoints.add(hole);
  74928. this._holes.push(holepoints);
  74929. this._eholes.push(this._epoints.length / 2);
  74930. this._addToepoint(hole);
  74931. return this;
  74932. };
  74933. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  74934. var _this = this;
  74935. if (updatable === void 0) { updatable = false; }
  74936. if (depth === void 0) { depth = 0; }
  74937. var result = new BABYLON.Mesh(this._name, this._scene);
  74938. var normals = new Array();
  74939. var positions = new Array();
  74940. var uvs = new Array();
  74941. var bounds = this._points.computeBounds();
  74942. this._points.elements.forEach(function (p) {
  74943. normals.push(0, 1.0, 0);
  74944. positions.push(p.x, 0, p.y);
  74945. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  74946. });
  74947. var indices = new Array();
  74948. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  74949. for (var i = 0; i < res.length; i++) {
  74950. indices.push(res[i]);
  74951. }
  74952. if (depth > 0) {
  74953. var positionscount = (positions.length / 3); //get the current pointcount
  74954. this._points.elements.forEach(function (p) {
  74955. normals.push(0, -1.0, 0);
  74956. positions.push(p.x, -depth, p.y);
  74957. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  74958. });
  74959. var totalCount = indices.length;
  74960. for (var i = 0; i < totalCount; i += 3) {
  74961. var i0 = indices[i + 0];
  74962. var i1 = indices[i + 1];
  74963. var i2 = indices[i + 2];
  74964. indices.push(i2 + positionscount);
  74965. indices.push(i1 + positionscount);
  74966. indices.push(i0 + positionscount);
  74967. }
  74968. //Add the sides
  74969. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  74970. this._holes.forEach(function (hole) {
  74971. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  74972. });
  74973. }
  74974. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  74975. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  74976. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  74977. result.setIndices(indices);
  74978. return result;
  74979. };
  74980. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  74981. var StartIndex = positions.length / 3;
  74982. var ulength = 0;
  74983. for (var i = 0; i < points.elements.length; i++) {
  74984. var p = points.elements[i];
  74985. var p1;
  74986. if ((i + 1) > points.elements.length - 1) {
  74987. p1 = points.elements[0];
  74988. }
  74989. else {
  74990. p1 = points.elements[i + 1];
  74991. }
  74992. positions.push(p.x, 0, p.y);
  74993. positions.push(p.x, -depth, p.y);
  74994. positions.push(p1.x, 0, p1.y);
  74995. positions.push(p1.x, -depth, p1.y);
  74996. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  74997. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  74998. var v3 = v2.subtract(v1);
  74999. var v4 = new BABYLON.Vector3(0, 1, 0);
  75000. var vn = BABYLON.Vector3.Cross(v3, v4);
  75001. vn = vn.normalize();
  75002. uvs.push(ulength / bounds.width, 0);
  75003. uvs.push(ulength / bounds.width, 1);
  75004. ulength += v3.length();
  75005. uvs.push((ulength / bounds.width), 0);
  75006. uvs.push((ulength / bounds.width), 1);
  75007. if (!flip) {
  75008. normals.push(-vn.x, -vn.y, -vn.z);
  75009. normals.push(-vn.x, -vn.y, -vn.z);
  75010. normals.push(-vn.x, -vn.y, -vn.z);
  75011. normals.push(-vn.x, -vn.y, -vn.z);
  75012. indices.push(StartIndex);
  75013. indices.push(StartIndex + 1);
  75014. indices.push(StartIndex + 2);
  75015. indices.push(StartIndex + 1);
  75016. indices.push(StartIndex + 3);
  75017. indices.push(StartIndex + 2);
  75018. }
  75019. else {
  75020. normals.push(vn.x, vn.y, vn.z);
  75021. normals.push(vn.x, vn.y, vn.z);
  75022. normals.push(vn.x, vn.y, vn.z);
  75023. normals.push(vn.x, vn.y, vn.z);
  75024. indices.push(StartIndex);
  75025. indices.push(StartIndex + 2);
  75026. indices.push(StartIndex + 1);
  75027. indices.push(StartIndex + 1);
  75028. indices.push(StartIndex + 2);
  75029. indices.push(StartIndex + 3);
  75030. }
  75031. StartIndex += 4;
  75032. }
  75033. ;
  75034. };
  75035. return PolygonMeshBuilder;
  75036. }());
  75037. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  75038. })(BABYLON || (BABYLON = {}));
  75039. //# sourceMappingURL=babylon.polygonMesh.js.map
  75040. var BABYLON;
  75041. (function (BABYLON) {
  75042. // Unique ID when we import meshes from Babylon to CSG
  75043. var currentCSGMeshId = 0;
  75044. // # class Vertex
  75045. // Represents a vertex of a polygon. Use your own vertex class instead of this
  75046. // one to provide additional features like texture coordinates and vertex
  75047. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  75048. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  75049. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  75050. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  75051. // is not used anywhere else.
  75052. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  75053. var Vertex = /** @class */ (function () {
  75054. function Vertex(pos, normal, uv) {
  75055. this.pos = pos;
  75056. this.normal = normal;
  75057. this.uv = uv;
  75058. }
  75059. Vertex.prototype.clone = function () {
  75060. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  75061. };
  75062. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  75063. // orientation of a polygon is flipped.
  75064. Vertex.prototype.flip = function () {
  75065. this.normal = this.normal.scale(-1);
  75066. };
  75067. // Create a new vertex between this vertex and `other` by linearly
  75068. // interpolating all properties using a parameter of `t`. Subclasses should
  75069. // override this to interpolate additional properties.
  75070. Vertex.prototype.interpolate = function (other, t) {
  75071. 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));
  75072. };
  75073. return Vertex;
  75074. }());
  75075. // # class Plane
  75076. // Represents a plane in 3D space.
  75077. var Plane = /** @class */ (function () {
  75078. function Plane(normal, w) {
  75079. this.normal = normal;
  75080. this.w = w;
  75081. }
  75082. Plane.FromPoints = function (a, b, c) {
  75083. var v0 = c.subtract(a);
  75084. var v1 = b.subtract(a);
  75085. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  75086. return null;
  75087. }
  75088. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  75089. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  75090. };
  75091. Plane.prototype.clone = function () {
  75092. return new Plane(this.normal.clone(), this.w);
  75093. };
  75094. Plane.prototype.flip = function () {
  75095. this.normal.scaleInPlace(-1);
  75096. this.w = -this.w;
  75097. };
  75098. // Split `polygon` by this plane if needed, then put the polygon or polygon
  75099. // fragments in the appropriate lists. Coplanar polygons go into either
  75100. // `coplanarFront` or `coplanarBack` depending on their orientation with
  75101. // respect to this plane. Polygons in front or in back of this plane go into
  75102. // either `front` or `back`.
  75103. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  75104. var COPLANAR = 0;
  75105. var FRONT = 1;
  75106. var BACK = 2;
  75107. var SPANNING = 3;
  75108. // Classify each point as well as the entire polygon into one of the above
  75109. // four classes.
  75110. var polygonType = 0;
  75111. var types = [];
  75112. var i;
  75113. var t;
  75114. for (i = 0; i < polygon.vertices.length; i++) {
  75115. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  75116. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  75117. polygonType |= type;
  75118. types.push(type);
  75119. }
  75120. // Put the polygon in the correct list, splitting it when necessary.
  75121. switch (polygonType) {
  75122. case COPLANAR:
  75123. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  75124. break;
  75125. case FRONT:
  75126. front.push(polygon);
  75127. break;
  75128. case BACK:
  75129. back.push(polygon);
  75130. break;
  75131. case SPANNING:
  75132. var f = [], b = [];
  75133. for (i = 0; i < polygon.vertices.length; i++) {
  75134. var j = (i + 1) % polygon.vertices.length;
  75135. var ti = types[i], tj = types[j];
  75136. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  75137. if (ti !== BACK)
  75138. f.push(vi);
  75139. if (ti !== FRONT)
  75140. b.push(ti !== BACK ? vi.clone() : vi);
  75141. if ((ti | tj) === SPANNING) {
  75142. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  75143. var v = vi.interpolate(vj, t);
  75144. f.push(v);
  75145. b.push(v.clone());
  75146. }
  75147. }
  75148. var poly;
  75149. if (f.length >= 3) {
  75150. poly = new Polygon(f, polygon.shared);
  75151. if (poly.plane)
  75152. front.push(poly);
  75153. }
  75154. if (b.length >= 3) {
  75155. poly = new Polygon(b, polygon.shared);
  75156. if (poly.plane)
  75157. back.push(poly);
  75158. }
  75159. break;
  75160. }
  75161. };
  75162. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  75163. // point is on the plane.
  75164. Plane.EPSILON = 1e-5;
  75165. return Plane;
  75166. }());
  75167. // # class Polygon
  75168. // Represents a convex polygon. The vertices used to initialize a polygon must
  75169. // be coplanar and form a convex loop.
  75170. //
  75171. // Each convex polygon has a `shared` property, which is shared between all
  75172. // polygons that are clones of each other or were split from the same polygon.
  75173. // This can be used to define per-polygon properties (such as surface color).
  75174. var Polygon = /** @class */ (function () {
  75175. function Polygon(vertices, shared) {
  75176. this.vertices = vertices;
  75177. this.shared = shared;
  75178. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  75179. }
  75180. Polygon.prototype.clone = function () {
  75181. var vertices = this.vertices.map(function (v) { return v.clone(); });
  75182. return new Polygon(vertices, this.shared);
  75183. };
  75184. Polygon.prototype.flip = function () {
  75185. this.vertices.reverse().map(function (v) { v.flip(); });
  75186. this.plane.flip();
  75187. };
  75188. return Polygon;
  75189. }());
  75190. // # class Node
  75191. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  75192. // by picking a polygon to split along. That polygon (and all other coplanar
  75193. // polygons) are added directly to that node and the other polygons are added to
  75194. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  75195. // no distinction between internal and leaf nodes.
  75196. var Node = /** @class */ (function () {
  75197. function Node(polygons) {
  75198. this.plane = null;
  75199. this.front = null;
  75200. this.back = null;
  75201. this.polygons = new Array();
  75202. if (polygons) {
  75203. this.build(polygons);
  75204. }
  75205. }
  75206. Node.prototype.clone = function () {
  75207. var node = new Node();
  75208. node.plane = this.plane && this.plane.clone();
  75209. node.front = this.front && this.front.clone();
  75210. node.back = this.back && this.back.clone();
  75211. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  75212. return node;
  75213. };
  75214. // Convert solid space to empty space and empty space to solid space.
  75215. Node.prototype.invert = function () {
  75216. for (var i = 0; i < this.polygons.length; i++) {
  75217. this.polygons[i].flip();
  75218. }
  75219. if (this.plane) {
  75220. this.plane.flip();
  75221. }
  75222. if (this.front) {
  75223. this.front.invert();
  75224. }
  75225. if (this.back) {
  75226. this.back.invert();
  75227. }
  75228. var temp = this.front;
  75229. this.front = this.back;
  75230. this.back = temp;
  75231. };
  75232. // Recursively remove all polygons in `polygons` that are inside this BSP
  75233. // tree.
  75234. Node.prototype.clipPolygons = function (polygons) {
  75235. if (!this.plane)
  75236. return polygons.slice();
  75237. var front = new Array(), back = new Array();
  75238. for (var i = 0; i < polygons.length; i++) {
  75239. this.plane.splitPolygon(polygons[i], front, back, front, back);
  75240. }
  75241. if (this.front) {
  75242. front = this.front.clipPolygons(front);
  75243. }
  75244. if (this.back) {
  75245. back = this.back.clipPolygons(back);
  75246. }
  75247. else {
  75248. back = [];
  75249. }
  75250. return front.concat(back);
  75251. };
  75252. // Remove all polygons in this BSP tree that are inside the other BSP tree
  75253. // `bsp`.
  75254. Node.prototype.clipTo = function (bsp) {
  75255. this.polygons = bsp.clipPolygons(this.polygons);
  75256. if (this.front)
  75257. this.front.clipTo(bsp);
  75258. if (this.back)
  75259. this.back.clipTo(bsp);
  75260. };
  75261. // Return a list of all polygons in this BSP tree.
  75262. Node.prototype.allPolygons = function () {
  75263. var polygons = this.polygons.slice();
  75264. if (this.front)
  75265. polygons = polygons.concat(this.front.allPolygons());
  75266. if (this.back)
  75267. polygons = polygons.concat(this.back.allPolygons());
  75268. return polygons;
  75269. };
  75270. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  75271. // new polygons are filtered down to the bottom of the tree and become new
  75272. // nodes there. Each set of polygons is partitioned using the first polygon
  75273. // (no heuristic is used to pick a good split).
  75274. Node.prototype.build = function (polygons) {
  75275. if (!polygons.length)
  75276. return;
  75277. if (!this.plane)
  75278. this.plane = polygons[0].plane.clone();
  75279. var front = new Array(), back = new Array();
  75280. for (var i = 0; i < polygons.length; i++) {
  75281. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  75282. }
  75283. if (front.length) {
  75284. if (!this.front)
  75285. this.front = new Node();
  75286. this.front.build(front);
  75287. }
  75288. if (back.length) {
  75289. if (!this.back)
  75290. this.back = new Node();
  75291. this.back.build(back);
  75292. }
  75293. };
  75294. return Node;
  75295. }());
  75296. var CSG = /** @class */ (function () {
  75297. function CSG() {
  75298. this.polygons = new Array();
  75299. }
  75300. // Convert BABYLON.Mesh to BABYLON.CSG
  75301. CSG.FromMesh = function (mesh) {
  75302. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  75303. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  75304. if (mesh instanceof BABYLON.Mesh) {
  75305. mesh.computeWorldMatrix(true);
  75306. matrix = mesh.getWorldMatrix();
  75307. meshPosition = mesh.position.clone();
  75308. meshRotation = mesh.rotation.clone();
  75309. if (mesh.rotationQuaternion) {
  75310. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  75311. }
  75312. meshScaling = mesh.scaling.clone();
  75313. }
  75314. else {
  75315. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  75316. }
  75317. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75318. var subMeshes = mesh.subMeshes;
  75319. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  75320. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  75321. vertices = [];
  75322. for (var j = 0; j < 3; j++) {
  75323. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  75324. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  75325. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  75326. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  75327. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  75328. vertex = new Vertex(position, normal, uv);
  75329. vertices.push(vertex);
  75330. }
  75331. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  75332. // To handle the case of degenerated triangle
  75333. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  75334. if (polygon.plane)
  75335. polygons.push(polygon);
  75336. }
  75337. }
  75338. var csg = CSG.FromPolygons(polygons);
  75339. csg.matrix = matrix;
  75340. csg.position = meshPosition;
  75341. csg.rotation = meshRotation;
  75342. csg.scaling = meshScaling;
  75343. csg.rotationQuaternion = meshRotationQuaternion;
  75344. currentCSGMeshId++;
  75345. return csg;
  75346. };
  75347. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  75348. CSG.FromPolygons = function (polygons) {
  75349. var csg = new CSG();
  75350. csg.polygons = polygons;
  75351. return csg;
  75352. };
  75353. CSG.prototype.clone = function () {
  75354. var csg = new CSG();
  75355. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  75356. csg.copyTransformAttributes(this);
  75357. return csg;
  75358. };
  75359. CSG.prototype.union = function (csg) {
  75360. var a = new Node(this.clone().polygons);
  75361. var b = new Node(csg.clone().polygons);
  75362. a.clipTo(b);
  75363. b.clipTo(a);
  75364. b.invert();
  75365. b.clipTo(a);
  75366. b.invert();
  75367. a.build(b.allPolygons());
  75368. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75369. };
  75370. CSG.prototype.unionInPlace = function (csg) {
  75371. var a = new Node(this.polygons);
  75372. var b = new Node(csg.polygons);
  75373. a.clipTo(b);
  75374. b.clipTo(a);
  75375. b.invert();
  75376. b.clipTo(a);
  75377. b.invert();
  75378. a.build(b.allPolygons());
  75379. this.polygons = a.allPolygons();
  75380. };
  75381. CSG.prototype.subtract = function (csg) {
  75382. var a = new Node(this.clone().polygons);
  75383. var b = new Node(csg.clone().polygons);
  75384. a.invert();
  75385. a.clipTo(b);
  75386. b.clipTo(a);
  75387. b.invert();
  75388. b.clipTo(a);
  75389. b.invert();
  75390. a.build(b.allPolygons());
  75391. a.invert();
  75392. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75393. };
  75394. CSG.prototype.subtractInPlace = function (csg) {
  75395. var a = new Node(this.polygons);
  75396. var b = new Node(csg.polygons);
  75397. a.invert();
  75398. a.clipTo(b);
  75399. b.clipTo(a);
  75400. b.invert();
  75401. b.clipTo(a);
  75402. b.invert();
  75403. a.build(b.allPolygons());
  75404. a.invert();
  75405. this.polygons = a.allPolygons();
  75406. };
  75407. CSG.prototype.intersect = function (csg) {
  75408. var a = new Node(this.clone().polygons);
  75409. var b = new Node(csg.clone().polygons);
  75410. a.invert();
  75411. b.clipTo(a);
  75412. b.invert();
  75413. a.clipTo(b);
  75414. b.clipTo(a);
  75415. a.build(b.allPolygons());
  75416. a.invert();
  75417. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75418. };
  75419. CSG.prototype.intersectInPlace = function (csg) {
  75420. var a = new Node(this.polygons);
  75421. var b = new Node(csg.polygons);
  75422. a.invert();
  75423. b.clipTo(a);
  75424. b.invert();
  75425. a.clipTo(b);
  75426. b.clipTo(a);
  75427. a.build(b.allPolygons());
  75428. a.invert();
  75429. this.polygons = a.allPolygons();
  75430. };
  75431. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  75432. // not modified.
  75433. CSG.prototype.inverse = function () {
  75434. var csg = this.clone();
  75435. csg.inverseInPlace();
  75436. return csg;
  75437. };
  75438. CSG.prototype.inverseInPlace = function () {
  75439. this.polygons.map(function (p) { p.flip(); });
  75440. };
  75441. // This is used to keep meshes transformations so they can be restored
  75442. // when we build back a Babylon Mesh
  75443. // NB : All CSG operations are performed in world coordinates
  75444. CSG.prototype.copyTransformAttributes = function (csg) {
  75445. this.matrix = csg.matrix;
  75446. this.position = csg.position;
  75447. this.rotation = csg.rotation;
  75448. this.scaling = csg.scaling;
  75449. this.rotationQuaternion = csg.rotationQuaternion;
  75450. return this;
  75451. };
  75452. // Build Raw mesh from CSG
  75453. // Coordinates here are in world space
  75454. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  75455. var matrix = this.matrix.clone();
  75456. matrix.invert();
  75457. 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;
  75458. if (keepSubMeshes) {
  75459. // Sort Polygons, since subMeshes are indices range
  75460. polygons.sort(function (a, b) {
  75461. if (a.shared.meshId === b.shared.meshId) {
  75462. return a.shared.subMeshId - b.shared.subMeshId;
  75463. }
  75464. else {
  75465. return a.shared.meshId - b.shared.meshId;
  75466. }
  75467. });
  75468. }
  75469. for (var i = 0, il = polygons.length; i < il; i++) {
  75470. polygon = polygons[i];
  75471. // Building SubMeshes
  75472. if (!subMesh_dict[polygon.shared.meshId]) {
  75473. subMesh_dict[polygon.shared.meshId] = {};
  75474. }
  75475. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  75476. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  75477. indexStart: +Infinity,
  75478. indexEnd: -Infinity,
  75479. materialIndex: polygon.shared.materialIndex
  75480. };
  75481. }
  75482. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  75483. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  75484. polygonIndices[0] = 0;
  75485. polygonIndices[1] = j - 1;
  75486. polygonIndices[2] = j;
  75487. for (var k = 0; k < 3; k++) {
  75488. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  75489. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  75490. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  75491. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  75492. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  75493. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  75494. // Check if 2 points can be merged
  75495. if (!(typeof vertex_idx !== 'undefined' &&
  75496. normals[vertex_idx * 3] === localNormal.x &&
  75497. normals[vertex_idx * 3 + 1] === localNormal.y &&
  75498. normals[vertex_idx * 3 + 2] === localNormal.z &&
  75499. uvs[vertex_idx * 2] === uv.x &&
  75500. uvs[vertex_idx * 2 + 1] === uv.y)) {
  75501. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  75502. uvs.push(uv.x, uv.y);
  75503. normals.push(normal.x, normal.y, normal.z);
  75504. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  75505. }
  75506. indices.push(vertex_idx);
  75507. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  75508. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  75509. currentIndex++;
  75510. }
  75511. }
  75512. }
  75513. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  75514. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  75515. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  75516. mesh.setIndices(indices, null);
  75517. if (keepSubMeshes) {
  75518. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  75519. var materialIndexOffset = 0, materialMaxIndex;
  75520. mesh.subMeshes = new Array();
  75521. for (var m in subMesh_dict) {
  75522. materialMaxIndex = -1;
  75523. for (var sm in subMesh_dict[m]) {
  75524. subMesh_obj = subMesh_dict[m][sm];
  75525. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  75526. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  75527. }
  75528. materialIndexOffset += ++materialMaxIndex;
  75529. }
  75530. }
  75531. return mesh;
  75532. };
  75533. // Build Mesh from CSG taking material and transforms into account
  75534. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  75535. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  75536. mesh.material = material;
  75537. mesh.position.copyFrom(this.position);
  75538. mesh.rotation.copyFrom(this.rotation);
  75539. if (this.rotationQuaternion) {
  75540. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  75541. }
  75542. mesh.scaling.copyFrom(this.scaling);
  75543. mesh.computeWorldMatrix(true);
  75544. return mesh;
  75545. };
  75546. return CSG;
  75547. }());
  75548. BABYLON.CSG = CSG;
  75549. })(BABYLON || (BABYLON = {}));
  75550. //# sourceMappingURL=babylon.csg.js.map
  75551. var BABYLON;
  75552. (function (BABYLON) {
  75553. var LensFlare = /** @class */ (function () {
  75554. function LensFlare(size, position, color, imgUrl, system) {
  75555. this.size = size;
  75556. this.position = position;
  75557. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  75558. this.color = color || new BABYLON.Color3(1, 1, 1);
  75559. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  75560. this._system = system;
  75561. system.lensFlares.push(this);
  75562. }
  75563. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  75564. return new LensFlare(size, position, color, imgUrl, system);
  75565. };
  75566. LensFlare.prototype.dispose = function () {
  75567. if (this.texture) {
  75568. this.texture.dispose();
  75569. }
  75570. // Remove from scene
  75571. var index = this._system.lensFlares.indexOf(this);
  75572. this._system.lensFlares.splice(index, 1);
  75573. };
  75574. ;
  75575. return LensFlare;
  75576. }());
  75577. BABYLON.LensFlare = LensFlare;
  75578. })(BABYLON || (BABYLON = {}));
  75579. //# sourceMappingURL=babylon.lensFlare.js.map
  75580. var BABYLON;
  75581. (function (BABYLON) {
  75582. var LensFlareSystem = /** @class */ (function () {
  75583. function LensFlareSystem(name, emitter, scene) {
  75584. this.name = name;
  75585. this.lensFlares = new Array();
  75586. this.borderLimit = 300;
  75587. this.viewportBorder = 0;
  75588. this.layerMask = 0x0FFFFFFF;
  75589. this._vertexBuffers = {};
  75590. this._isEnabled = true;
  75591. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75592. this._emitter = emitter;
  75593. this.id = name;
  75594. scene.lensFlareSystems.push(this);
  75595. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  75596. var engine = scene.getEngine();
  75597. // VBO
  75598. var vertices = [];
  75599. vertices.push(1, 1);
  75600. vertices.push(-1, 1);
  75601. vertices.push(-1, -1);
  75602. vertices.push(1, -1);
  75603. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75604. // Indices
  75605. var indices = [];
  75606. indices.push(0);
  75607. indices.push(1);
  75608. indices.push(2);
  75609. indices.push(0);
  75610. indices.push(2);
  75611. indices.push(3);
  75612. this._indexBuffer = engine.createIndexBuffer(indices);
  75613. // Effects
  75614. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  75615. }
  75616. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  75617. get: function () {
  75618. return this._isEnabled;
  75619. },
  75620. set: function (value) {
  75621. this._isEnabled = value;
  75622. },
  75623. enumerable: true,
  75624. configurable: true
  75625. });
  75626. LensFlareSystem.prototype.getScene = function () {
  75627. return this._scene;
  75628. };
  75629. LensFlareSystem.prototype.getEmitter = function () {
  75630. return this._emitter;
  75631. };
  75632. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  75633. this._emitter = newEmitter;
  75634. };
  75635. LensFlareSystem.prototype.getEmitterPosition = function () {
  75636. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  75637. };
  75638. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  75639. var position = this.getEmitterPosition();
  75640. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  75641. this._positionX = position.x;
  75642. this._positionY = position.y;
  75643. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  75644. if (this.viewportBorder > 0) {
  75645. globalViewport.x -= this.viewportBorder;
  75646. globalViewport.y -= this.viewportBorder;
  75647. globalViewport.width += this.viewportBorder * 2;
  75648. globalViewport.height += this.viewportBorder * 2;
  75649. position.x += this.viewportBorder;
  75650. position.y += this.viewportBorder;
  75651. this._positionX += this.viewportBorder;
  75652. this._positionY += this.viewportBorder;
  75653. }
  75654. if (position.z > 0) {
  75655. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  75656. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  75657. return true;
  75658. }
  75659. return true;
  75660. }
  75661. return false;
  75662. };
  75663. LensFlareSystem.prototype._isVisible = function () {
  75664. if (!this._isEnabled || !this._scene.activeCamera) {
  75665. return false;
  75666. }
  75667. var emitterPosition = this.getEmitterPosition();
  75668. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  75669. var distance = direction.length();
  75670. direction.normalize();
  75671. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  75672. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  75673. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  75674. };
  75675. LensFlareSystem.prototype.render = function () {
  75676. if (!this._effect.isReady() || !this._scene.activeCamera)
  75677. return false;
  75678. var engine = this._scene.getEngine();
  75679. var viewport = this._scene.activeCamera.viewport;
  75680. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  75681. // Position
  75682. if (!this.computeEffectivePosition(globalViewport)) {
  75683. return false;
  75684. }
  75685. // Visibility
  75686. if (!this._isVisible()) {
  75687. return false;
  75688. }
  75689. // Intensity
  75690. var awayX;
  75691. var awayY;
  75692. if (this._positionX < this.borderLimit + globalViewport.x) {
  75693. awayX = this.borderLimit + globalViewport.x - this._positionX;
  75694. }
  75695. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  75696. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  75697. }
  75698. else {
  75699. awayX = 0;
  75700. }
  75701. if (this._positionY < this.borderLimit + globalViewport.y) {
  75702. awayY = this.borderLimit + globalViewport.y - this._positionY;
  75703. }
  75704. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  75705. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  75706. }
  75707. else {
  75708. awayY = 0;
  75709. }
  75710. var away = (awayX > awayY) ? awayX : awayY;
  75711. away -= this.viewportBorder;
  75712. if (away > this.borderLimit) {
  75713. away = this.borderLimit;
  75714. }
  75715. var intensity = 1.0 - (away / this.borderLimit);
  75716. if (intensity < 0) {
  75717. return false;
  75718. }
  75719. if (intensity > 1.0) {
  75720. intensity = 1.0;
  75721. }
  75722. if (this.viewportBorder > 0) {
  75723. globalViewport.x += this.viewportBorder;
  75724. globalViewport.y += this.viewportBorder;
  75725. globalViewport.width -= this.viewportBorder * 2;
  75726. globalViewport.height -= this.viewportBorder * 2;
  75727. this._positionX -= this.viewportBorder;
  75728. this._positionY -= this.viewportBorder;
  75729. }
  75730. // Position
  75731. var centerX = globalViewport.x + globalViewport.width / 2;
  75732. var centerY = globalViewport.y + globalViewport.height / 2;
  75733. var distX = centerX - this._positionX;
  75734. var distY = centerY - this._positionY;
  75735. // Effects
  75736. engine.enableEffect(this._effect);
  75737. engine.setState(false);
  75738. engine.setDepthBuffer(false);
  75739. // VBOs
  75740. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  75741. // Flares
  75742. for (var index = 0; index < this.lensFlares.length; index++) {
  75743. var flare = this.lensFlares[index];
  75744. engine.setAlphaMode(flare.alphaMode);
  75745. var x = centerX - (distX * flare.position);
  75746. var y = centerY - (distY * flare.position);
  75747. var cw = flare.size;
  75748. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  75749. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  75750. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  75751. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  75752. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  75753. // Texture
  75754. this._effect.setTexture("textureSampler", flare.texture);
  75755. // Color
  75756. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  75757. // Draw order
  75758. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75759. }
  75760. engine.setDepthBuffer(true);
  75761. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75762. return true;
  75763. };
  75764. LensFlareSystem.prototype.dispose = function () {
  75765. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75766. if (vertexBuffer) {
  75767. vertexBuffer.dispose();
  75768. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75769. }
  75770. if (this._indexBuffer) {
  75771. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75772. this._indexBuffer = null;
  75773. }
  75774. while (this.lensFlares.length) {
  75775. this.lensFlares[0].dispose();
  75776. }
  75777. // Remove from scene
  75778. var index = this._scene.lensFlareSystems.indexOf(this);
  75779. this._scene.lensFlareSystems.splice(index, 1);
  75780. };
  75781. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  75782. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  75783. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  75784. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  75785. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  75786. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  75787. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  75788. var parsedFlare = parsedLensFlareSystem.flares[index];
  75789. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  75790. }
  75791. return lensFlareSystem;
  75792. };
  75793. LensFlareSystem.prototype.serialize = function () {
  75794. var serializationObject = {};
  75795. serializationObject.id = this.id;
  75796. serializationObject.name = this.name;
  75797. serializationObject.emitterId = this.getEmitter().id;
  75798. serializationObject.borderLimit = this.borderLimit;
  75799. serializationObject.flares = [];
  75800. for (var index = 0; index < this.lensFlares.length; index++) {
  75801. var flare = this.lensFlares[index];
  75802. serializationObject.flares.push({
  75803. size: flare.size,
  75804. position: flare.position,
  75805. color: flare.color.asArray(),
  75806. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  75807. });
  75808. }
  75809. return serializationObject;
  75810. };
  75811. return LensFlareSystem;
  75812. }());
  75813. BABYLON.LensFlareSystem = LensFlareSystem;
  75814. })(BABYLON || (BABYLON = {}));
  75815. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  75816. var BABYLON;
  75817. (function (BABYLON) {
  75818. /**
  75819. * This is a holder class for the physics joint created by the physics plugin.
  75820. * It holds a set of functions to control the underlying joint.
  75821. */
  75822. var PhysicsJoint = /** @class */ (function () {
  75823. function PhysicsJoint(type, jointData) {
  75824. this.type = type;
  75825. this.jointData = jointData;
  75826. jointData.nativeParams = jointData.nativeParams || {};
  75827. }
  75828. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  75829. get: function () {
  75830. return this._physicsJoint;
  75831. },
  75832. set: function (newJoint) {
  75833. if (this._physicsJoint) {
  75834. //remove from the wolrd
  75835. }
  75836. this._physicsJoint = newJoint;
  75837. },
  75838. enumerable: true,
  75839. configurable: true
  75840. });
  75841. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  75842. set: function (physicsPlugin) {
  75843. this._physicsPlugin = physicsPlugin;
  75844. },
  75845. enumerable: true,
  75846. configurable: true
  75847. });
  75848. /**
  75849. * Execute a function that is physics-plugin specific.
  75850. * @param {Function} func the function that will be executed.
  75851. * It accepts two parameters: the physics world and the physics joint.
  75852. */
  75853. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  75854. func(this._physicsPlugin.world, this._physicsJoint);
  75855. };
  75856. //TODO check if the native joints are the same
  75857. //Joint Types
  75858. PhysicsJoint.DistanceJoint = 0;
  75859. PhysicsJoint.HingeJoint = 1;
  75860. PhysicsJoint.BallAndSocketJoint = 2;
  75861. PhysicsJoint.WheelJoint = 3;
  75862. PhysicsJoint.SliderJoint = 4;
  75863. //OIMO
  75864. PhysicsJoint.PrismaticJoint = 5;
  75865. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  75866. PhysicsJoint.UniversalJoint = 6;
  75867. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  75868. //Cannon
  75869. //Similar to a Ball-Joint. Different in params
  75870. PhysicsJoint.PointToPointJoint = 8;
  75871. //Cannon only at the moment
  75872. PhysicsJoint.SpringJoint = 9;
  75873. PhysicsJoint.LockJoint = 10;
  75874. return PhysicsJoint;
  75875. }());
  75876. BABYLON.PhysicsJoint = PhysicsJoint;
  75877. /**
  75878. * A class representing a physics distance joint.
  75879. */
  75880. var DistanceJoint = /** @class */ (function (_super) {
  75881. __extends(DistanceJoint, _super);
  75882. function DistanceJoint(jointData) {
  75883. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  75884. }
  75885. /**
  75886. * Update the predefined distance.
  75887. */
  75888. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  75889. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  75890. };
  75891. return DistanceJoint;
  75892. }(PhysicsJoint));
  75893. BABYLON.DistanceJoint = DistanceJoint;
  75894. var MotorEnabledJoint = /** @class */ (function (_super) {
  75895. __extends(MotorEnabledJoint, _super);
  75896. function MotorEnabledJoint(type, jointData) {
  75897. return _super.call(this, type, jointData) || this;
  75898. }
  75899. /**
  75900. * Set the motor values.
  75901. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75902. * @param {number} force the force to apply
  75903. * @param {number} maxForce max force for this motor.
  75904. */
  75905. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  75906. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75907. };
  75908. /**
  75909. * Set the motor's limits.
  75910. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75911. */
  75912. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75913. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75914. };
  75915. return MotorEnabledJoint;
  75916. }(PhysicsJoint));
  75917. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  75918. /**
  75919. * This class represents a single hinge physics joint
  75920. */
  75921. var HingeJoint = /** @class */ (function (_super) {
  75922. __extends(HingeJoint, _super);
  75923. function HingeJoint(jointData) {
  75924. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  75925. }
  75926. /**
  75927. * Set the motor values.
  75928. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75929. * @param {number} force the force to apply
  75930. * @param {number} maxForce max force for this motor.
  75931. */
  75932. HingeJoint.prototype.setMotor = function (force, maxForce) {
  75933. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75934. };
  75935. /**
  75936. * Set the motor's limits.
  75937. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75938. */
  75939. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75940. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75941. };
  75942. return HingeJoint;
  75943. }(MotorEnabledJoint));
  75944. BABYLON.HingeJoint = HingeJoint;
  75945. /**
  75946. * This class represents a dual hinge physics joint (same as wheel joint)
  75947. */
  75948. var Hinge2Joint = /** @class */ (function (_super) {
  75949. __extends(Hinge2Joint, _super);
  75950. function Hinge2Joint(jointData) {
  75951. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  75952. }
  75953. /**
  75954. * Set the motor values.
  75955. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75956. * @param {number} force the force to apply
  75957. * @param {number} maxForce max force for this motor.
  75958. * @param {motorIndex} the motor's index, 0 or 1.
  75959. */
  75960. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  75961. if (motorIndex === void 0) { motorIndex = 0; }
  75962. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  75963. };
  75964. /**
  75965. * Set the motor limits.
  75966. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75967. * @param {number} upperLimit the upper limit
  75968. * @param {number} lowerLimit lower limit
  75969. * @param {motorIndex} the motor's index, 0 or 1.
  75970. */
  75971. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  75972. if (motorIndex === void 0) { motorIndex = 0; }
  75973. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  75974. };
  75975. return Hinge2Joint;
  75976. }(MotorEnabledJoint));
  75977. BABYLON.Hinge2Joint = Hinge2Joint;
  75978. })(BABYLON || (BABYLON = {}));
  75979. //# sourceMappingURL=babylon.physicsJoint.js.map
  75980. var BABYLON;
  75981. (function (BABYLON) {
  75982. var PhysicsImpostor = /** @class */ (function () {
  75983. function PhysicsImpostor(object, type, _options, _scene) {
  75984. if (_options === void 0) { _options = { mass: 0 }; }
  75985. var _this = this;
  75986. this.object = object;
  75987. this.type = type;
  75988. this._options = _options;
  75989. this._scene = _scene;
  75990. this._bodyUpdateRequired = false;
  75991. this._onBeforePhysicsStepCallbacks = new Array();
  75992. this._onAfterPhysicsStepCallbacks = new Array();
  75993. this._onPhysicsCollideCallbacks = [];
  75994. this._deltaPosition = BABYLON.Vector3.Zero();
  75995. this._isDisposed = false;
  75996. //temp variables for parent rotation calculations
  75997. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  75998. this._tmpQuat = new BABYLON.Quaternion();
  75999. this._tmpQuat2 = new BABYLON.Quaternion();
  76000. /**
  76001. * this function is executed by the physics engine.
  76002. */
  76003. this.beforeStep = function () {
  76004. if (!_this._physicsEngine) {
  76005. return;
  76006. }
  76007. _this.object.translate(_this._deltaPosition, -1);
  76008. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  76009. _this.object.computeWorldMatrix(false);
  76010. if (_this.object.parent && _this.object.rotationQuaternion) {
  76011. _this.getParentsRotation();
  76012. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  76013. }
  76014. else {
  76015. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  76016. }
  76017. if (!_this._options.disableBidirectionalTransformation) {
  76018. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  76019. }
  76020. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  76021. func(_this);
  76022. });
  76023. };
  76024. /**
  76025. * this function is executed by the physics engine.
  76026. */
  76027. this.afterStep = function () {
  76028. if (!_this._physicsEngine) {
  76029. return;
  76030. }
  76031. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  76032. func(_this);
  76033. });
  76034. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  76035. // object has now its world rotation. needs to be converted to local.
  76036. if (_this.object.parent && _this.object.rotationQuaternion) {
  76037. _this.getParentsRotation();
  76038. _this._tmpQuat.conjugateInPlace();
  76039. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  76040. }
  76041. // take the position set and make it the absolute position of this object.
  76042. _this.object.setAbsolutePosition(_this.object.position);
  76043. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  76044. _this.object.translate(_this._deltaPosition, 1);
  76045. };
  76046. /**
  76047. * Legacy collision detection event support
  76048. */
  76049. this.onCollideEvent = null;
  76050. //event and body object due to cannon's event-based architecture.
  76051. this.onCollide = function (e) {
  76052. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  76053. return;
  76054. }
  76055. if (!_this._physicsEngine) {
  76056. return;
  76057. }
  76058. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  76059. if (otherImpostor) {
  76060. // Legacy collision detection event support
  76061. if (_this.onCollideEvent) {
  76062. _this.onCollideEvent(_this, otherImpostor);
  76063. }
  76064. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  76065. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  76066. }).forEach(function (obj) {
  76067. obj.callback(_this, otherImpostor);
  76068. });
  76069. }
  76070. };
  76071. //sanity check!
  76072. if (!this.object) {
  76073. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  76074. return;
  76075. }
  76076. //legacy support for old syntax.
  76077. if (!this._scene && object.getScene) {
  76078. this._scene = object.getScene();
  76079. }
  76080. if (!this._scene) {
  76081. return;
  76082. }
  76083. this._physicsEngine = this._scene.getPhysicsEngine();
  76084. if (!this._physicsEngine) {
  76085. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  76086. }
  76087. else {
  76088. //set the object's quaternion, if not set
  76089. if (!this.object.rotationQuaternion) {
  76090. if (this.object.rotation) {
  76091. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  76092. }
  76093. else {
  76094. this.object.rotationQuaternion = new BABYLON.Quaternion();
  76095. }
  76096. }
  76097. //default options params
  76098. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  76099. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  76100. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  76101. this._joints = [];
  76102. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  76103. if (!this.object.parent || this._options.ignoreParent) {
  76104. this._init();
  76105. }
  76106. else if (this.object.parent.physicsImpostor) {
  76107. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  76108. }
  76109. }
  76110. }
  76111. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  76112. get: function () {
  76113. return this._isDisposed;
  76114. },
  76115. enumerable: true,
  76116. configurable: true
  76117. });
  76118. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  76119. get: function () {
  76120. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  76121. },
  76122. set: function (value) {
  76123. this.setMass(value);
  76124. },
  76125. enumerable: true,
  76126. configurable: true
  76127. });
  76128. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  76129. get: function () {
  76130. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  76131. },
  76132. set: function (value) {
  76133. if (!this._physicsEngine) {
  76134. return;
  76135. }
  76136. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  76137. },
  76138. enumerable: true,
  76139. configurable: true
  76140. });
  76141. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  76142. get: function () {
  76143. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  76144. },
  76145. set: function (value) {
  76146. if (!this._physicsEngine) {
  76147. return;
  76148. }
  76149. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  76150. },
  76151. enumerable: true,
  76152. configurable: true
  76153. });
  76154. /**
  76155. * This function will completly initialize this impostor.
  76156. * It will create a new body - but only if this mesh has no parent.
  76157. * If it has, this impostor will not be used other than to define the impostor
  76158. * of the child mesh.
  76159. */
  76160. PhysicsImpostor.prototype._init = function () {
  76161. if (!this._physicsEngine) {
  76162. return;
  76163. }
  76164. this._physicsEngine.removeImpostor(this);
  76165. this.physicsBody = null;
  76166. this._parent = this._parent || this._getPhysicsParent();
  76167. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  76168. this._physicsEngine.addImpostor(this);
  76169. }
  76170. };
  76171. PhysicsImpostor.prototype._getPhysicsParent = function () {
  76172. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  76173. var parentMesh = this.object.parent;
  76174. return parentMesh.physicsImpostor;
  76175. }
  76176. return null;
  76177. };
  76178. /**
  76179. * Should a new body be generated.
  76180. */
  76181. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  76182. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  76183. };
  76184. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  76185. this.forceUpdate();
  76186. };
  76187. /**
  76188. * Force a regeneration of this or the parent's impostor's body.
  76189. * Use under cautious - This will remove all joints already implemented.
  76190. */
  76191. PhysicsImpostor.prototype.forceUpdate = function () {
  76192. this._init();
  76193. if (this.parent && !this._options.ignoreParent) {
  76194. this.parent.forceUpdate();
  76195. }
  76196. };
  76197. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  76198. /*public get mesh(): AbstractMesh {
  76199. return this._mesh;
  76200. }*/
  76201. /**
  76202. * Gets the body that holds this impostor. Either its own, or its parent.
  76203. */
  76204. get: function () {
  76205. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  76206. },
  76207. /**
  76208. * Set the physics body. Used mainly by the physics engine/plugin
  76209. */
  76210. set: function (physicsBody) {
  76211. if (this._physicsBody && this._physicsEngine) {
  76212. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  76213. }
  76214. this._physicsBody = physicsBody;
  76215. this.resetUpdateFlags();
  76216. },
  76217. enumerable: true,
  76218. configurable: true
  76219. });
  76220. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  76221. get: function () {
  76222. return !this._options.ignoreParent && this._parent ? this._parent : null;
  76223. },
  76224. set: function (value) {
  76225. this._parent = value;
  76226. },
  76227. enumerable: true,
  76228. configurable: true
  76229. });
  76230. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  76231. this._bodyUpdateRequired = false;
  76232. };
  76233. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  76234. if (this.object.getBoundingInfo) {
  76235. var q = this.object.rotationQuaternion;
  76236. //reset rotation
  76237. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  76238. //calculate the world matrix with no rotation
  76239. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76240. var boundingInfo = this.object.getBoundingInfo();
  76241. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  76242. //bring back the rotation
  76243. this.object.rotationQuaternion = q;
  76244. //calculate the world matrix with the new rotation
  76245. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76246. return size;
  76247. }
  76248. else {
  76249. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  76250. }
  76251. };
  76252. PhysicsImpostor.prototype.getObjectCenter = function () {
  76253. if (this.object.getBoundingInfo) {
  76254. var boundingInfo = this.object.getBoundingInfo();
  76255. return boundingInfo.boundingBox.centerWorld;
  76256. }
  76257. else {
  76258. return this.object.position;
  76259. }
  76260. };
  76261. /**
  76262. * Get a specific parametes from the options parameter.
  76263. */
  76264. PhysicsImpostor.prototype.getParam = function (paramName) {
  76265. return this._options[paramName];
  76266. };
  76267. /**
  76268. * Sets a specific parameter in the options given to the physics plugin
  76269. */
  76270. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  76271. this._options[paramName] = value;
  76272. this._bodyUpdateRequired = true;
  76273. };
  76274. /**
  76275. * Specifically change the body's mass option. Won't recreate the physics body object
  76276. */
  76277. PhysicsImpostor.prototype.setMass = function (mass) {
  76278. if (this.getParam("mass") !== mass) {
  76279. this.setParam("mass", mass);
  76280. }
  76281. if (this._physicsEngine) {
  76282. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  76283. }
  76284. };
  76285. PhysicsImpostor.prototype.getLinearVelocity = function () {
  76286. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  76287. };
  76288. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  76289. if (this._physicsEngine) {
  76290. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  76291. }
  76292. };
  76293. PhysicsImpostor.prototype.getAngularVelocity = function () {
  76294. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  76295. };
  76296. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  76297. if (this._physicsEngine) {
  76298. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  76299. }
  76300. };
  76301. /**
  76302. * Execute a function with the physics plugin native code.
  76303. * Provide a function the will have two variables - the world object and the physics body object.
  76304. */
  76305. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  76306. if (this._physicsEngine) {
  76307. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  76308. }
  76309. };
  76310. /**
  76311. * Register a function that will be executed before the physics world is stepping forward.
  76312. */
  76313. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  76314. this._onBeforePhysicsStepCallbacks.push(func);
  76315. };
  76316. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  76317. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  76318. if (index > -1) {
  76319. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  76320. }
  76321. else {
  76322. BABYLON.Tools.Warn("Function to remove was not found");
  76323. }
  76324. };
  76325. /**
  76326. * Register a function that will be executed after the physics step
  76327. */
  76328. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  76329. this._onAfterPhysicsStepCallbacks.push(func);
  76330. };
  76331. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  76332. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  76333. if (index > -1) {
  76334. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  76335. }
  76336. else {
  76337. BABYLON.Tools.Warn("Function to remove was not found");
  76338. }
  76339. };
  76340. /**
  76341. * register a function that will be executed when this impostor collides against a different body.
  76342. */
  76343. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  76344. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76345. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  76346. };
  76347. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  76348. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76349. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  76350. if (index > -1) {
  76351. this._onPhysicsCollideCallbacks.splice(index, 1);
  76352. }
  76353. else {
  76354. BABYLON.Tools.Warn("Function to remove was not found");
  76355. }
  76356. };
  76357. PhysicsImpostor.prototype.getParentsRotation = function () {
  76358. var parent = this.object.parent;
  76359. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  76360. while (parent) {
  76361. if (parent.rotationQuaternion) {
  76362. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  76363. }
  76364. else {
  76365. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  76366. }
  76367. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  76368. parent = parent.parent;
  76369. }
  76370. return this._tmpQuat;
  76371. };
  76372. /**
  76373. * Apply a force
  76374. */
  76375. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  76376. if (this._physicsEngine) {
  76377. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  76378. }
  76379. return this;
  76380. };
  76381. /**
  76382. * Apply an impulse
  76383. */
  76384. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  76385. if (this._physicsEngine) {
  76386. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  76387. }
  76388. return this;
  76389. };
  76390. /**
  76391. * A help function to create a joint.
  76392. */
  76393. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  76394. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  76395. this.addJoint(otherImpostor, joint);
  76396. return this;
  76397. };
  76398. /**
  76399. * Add a joint to this impostor with a different impostor.
  76400. */
  76401. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  76402. this._joints.push({
  76403. otherImpostor: otherImpostor,
  76404. joint: joint
  76405. });
  76406. if (this._physicsEngine) {
  76407. this._physicsEngine.addJoint(this, otherImpostor, joint);
  76408. }
  76409. return this;
  76410. };
  76411. /**
  76412. * Will keep this body still, in a sleep mode.
  76413. */
  76414. PhysicsImpostor.prototype.sleep = function () {
  76415. if (this._physicsEngine) {
  76416. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  76417. }
  76418. return this;
  76419. };
  76420. /**
  76421. * Wake the body up.
  76422. */
  76423. PhysicsImpostor.prototype.wakeUp = function () {
  76424. if (this._physicsEngine) {
  76425. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  76426. }
  76427. return this;
  76428. };
  76429. PhysicsImpostor.prototype.clone = function (newObject) {
  76430. if (!newObject)
  76431. return null;
  76432. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  76433. };
  76434. PhysicsImpostor.prototype.dispose = function () {
  76435. var _this = this;
  76436. //no dispose if no physics engine is available.
  76437. if (!this._physicsEngine) {
  76438. return;
  76439. }
  76440. this._joints.forEach(function (j) {
  76441. if (_this._physicsEngine) {
  76442. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  76443. }
  76444. });
  76445. //dispose the physics body
  76446. this._physicsEngine.removeImpostor(this);
  76447. if (this.parent) {
  76448. this.parent.forceUpdate();
  76449. }
  76450. else {
  76451. /*this._object.getChildMeshes().forEach(function(mesh) {
  76452. if (mesh.physicsImpostor) {
  76453. if (disposeChildren) {
  76454. mesh.physicsImpostor.dispose();
  76455. mesh.physicsImpostor = null;
  76456. }
  76457. }
  76458. })*/
  76459. }
  76460. this._isDisposed = true;
  76461. };
  76462. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  76463. this._deltaPosition.copyFrom(position);
  76464. };
  76465. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  76466. if (!this._deltaRotation) {
  76467. this._deltaRotation = new BABYLON.Quaternion();
  76468. }
  76469. this._deltaRotation.copyFrom(rotation);
  76470. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  76471. };
  76472. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  76473. if (this._physicsEngine) {
  76474. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  76475. }
  76476. return this;
  76477. };
  76478. PhysicsImpostor.prototype.getRadius = function () {
  76479. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  76480. };
  76481. /**
  76482. * Sync a bone with this impostor
  76483. * @param bone The bone to sync to the impostor.
  76484. * @param boneMesh The mesh that the bone is influencing.
  76485. * @param jointPivot The pivot of the joint / bone in local space.
  76486. * @param distToJoint Optional distance from the impostor to the joint.
  76487. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76488. */
  76489. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  76490. var tempVec = PhysicsImpostor._tmpVecs[0];
  76491. var mesh = this.object;
  76492. if (mesh.rotationQuaternion) {
  76493. if (adjustRotation) {
  76494. var tempQuat = PhysicsImpostor._tmpQuat;
  76495. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  76496. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  76497. }
  76498. else {
  76499. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  76500. }
  76501. }
  76502. tempVec.x = 0;
  76503. tempVec.y = 0;
  76504. tempVec.z = 0;
  76505. if (jointPivot) {
  76506. tempVec.x = jointPivot.x;
  76507. tempVec.y = jointPivot.y;
  76508. tempVec.z = jointPivot.z;
  76509. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  76510. if (distToJoint === undefined || distToJoint === null) {
  76511. distToJoint = jointPivot.length();
  76512. }
  76513. tempVec.x *= distToJoint;
  76514. tempVec.y *= distToJoint;
  76515. tempVec.z *= distToJoint;
  76516. }
  76517. if (bone.getParent()) {
  76518. tempVec.addInPlace(mesh.getAbsolutePosition());
  76519. bone.setAbsolutePosition(tempVec, boneMesh);
  76520. }
  76521. else {
  76522. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  76523. boneMesh.position.x -= tempVec.x;
  76524. boneMesh.position.y -= tempVec.y;
  76525. boneMesh.position.z -= tempVec.z;
  76526. }
  76527. };
  76528. /**
  76529. * Sync impostor to a bone
  76530. * @param bone The bone that the impostor will be synced to.
  76531. * @param boneMesh The mesh that the bone is influencing.
  76532. * @param jointPivot The pivot of the joint / bone in local space.
  76533. * @param distToJoint Optional distance from the impostor to the joint.
  76534. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76535. * @param boneAxis Optional vector3 axis the bone is aligned with
  76536. */
  76537. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  76538. var mesh = this.object;
  76539. if (mesh.rotationQuaternion) {
  76540. if (adjustRotation) {
  76541. var tempQuat = PhysicsImpostor._tmpQuat;
  76542. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  76543. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  76544. }
  76545. else {
  76546. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  76547. }
  76548. }
  76549. var pos = PhysicsImpostor._tmpVecs[0];
  76550. var boneDir = PhysicsImpostor._tmpVecs[1];
  76551. if (!boneAxis) {
  76552. boneAxis = PhysicsImpostor._tmpVecs[2];
  76553. boneAxis.x = 0;
  76554. boneAxis.y = 1;
  76555. boneAxis.z = 0;
  76556. }
  76557. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  76558. bone.getAbsolutePositionToRef(boneMesh, pos);
  76559. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  76560. distToJoint = jointPivot.length();
  76561. }
  76562. if (distToJoint !== undefined && distToJoint !== null) {
  76563. pos.x += boneDir.x * distToJoint;
  76564. pos.y += boneDir.y * distToJoint;
  76565. pos.z += boneDir.z * distToJoint;
  76566. }
  76567. mesh.setAbsolutePosition(pos);
  76568. };
  76569. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  76570. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  76571. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76572. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  76573. //Impostor types
  76574. PhysicsImpostor.NoImpostor = 0;
  76575. PhysicsImpostor.SphereImpostor = 1;
  76576. PhysicsImpostor.BoxImpostor = 2;
  76577. PhysicsImpostor.PlaneImpostor = 3;
  76578. PhysicsImpostor.MeshImpostor = 4;
  76579. PhysicsImpostor.CylinderImpostor = 7;
  76580. PhysicsImpostor.ParticleImpostor = 8;
  76581. PhysicsImpostor.HeightmapImpostor = 9;
  76582. return PhysicsImpostor;
  76583. }());
  76584. BABYLON.PhysicsImpostor = PhysicsImpostor;
  76585. })(BABYLON || (BABYLON = {}));
  76586. //# sourceMappingURL=babylon.physicsImpostor.js.map
  76587. var BABYLON;
  76588. (function (BABYLON) {
  76589. var PhysicsEngine = /** @class */ (function () {
  76590. function PhysicsEngine(gravity, _physicsPlugin) {
  76591. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  76592. this._physicsPlugin = _physicsPlugin;
  76593. //new methods and parameters
  76594. this._impostors = [];
  76595. this._joints = [];
  76596. if (!this._physicsPlugin.isSupported()) {
  76597. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  76598. + "Please make sure it is included.");
  76599. }
  76600. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  76601. this.setGravity(gravity);
  76602. this.setTimeStep();
  76603. }
  76604. PhysicsEngine.prototype.setGravity = function (gravity) {
  76605. this.gravity = gravity;
  76606. this._physicsPlugin.setGravity(this.gravity);
  76607. };
  76608. /**
  76609. * Set the time step of the physics engine.
  76610. * default is 1/60.
  76611. * To slow it down, enter 1/600 for example.
  76612. * To speed it up, 1/30
  76613. * @param {number} newTimeStep the new timestep to apply to this world.
  76614. */
  76615. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  76616. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  76617. this._physicsPlugin.setTimeStep(newTimeStep);
  76618. };
  76619. /**
  76620. * Get the time step of the physics engine.
  76621. */
  76622. PhysicsEngine.prototype.getTimeStep = function () {
  76623. return this._physicsPlugin.getTimeStep();
  76624. };
  76625. PhysicsEngine.prototype.dispose = function () {
  76626. this._impostors.forEach(function (impostor) {
  76627. impostor.dispose();
  76628. });
  76629. this._physicsPlugin.dispose();
  76630. };
  76631. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  76632. return this._physicsPlugin.name;
  76633. };
  76634. /**
  76635. * Adding a new impostor for the impostor tracking.
  76636. * This will be done by the impostor itself.
  76637. * @param {PhysicsImpostor} impostor the impostor to add
  76638. */
  76639. PhysicsEngine.prototype.addImpostor = function (impostor) {
  76640. impostor.uniqueId = this._impostors.push(impostor);
  76641. //if no parent, generate the body
  76642. if (!impostor.parent) {
  76643. this._physicsPlugin.generatePhysicsBody(impostor);
  76644. }
  76645. };
  76646. /**
  76647. * Remove an impostor from the engine.
  76648. * This impostor and its mesh will not longer be updated by the physics engine.
  76649. * @param {PhysicsImpostor} impostor the impostor to remove
  76650. */
  76651. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  76652. var index = this._impostors.indexOf(impostor);
  76653. if (index > -1) {
  76654. var removed = this._impostors.splice(index, 1);
  76655. //Is it needed?
  76656. if (removed.length) {
  76657. //this will also remove it from the world.
  76658. removed[0].physicsBody = null;
  76659. }
  76660. }
  76661. };
  76662. /**
  76663. * Add a joint to the physics engine
  76664. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  76665. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  76666. * @param {PhysicsJoint} the joint that will connect both impostors.
  76667. */
  76668. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  76669. var impostorJoint = {
  76670. mainImpostor: mainImpostor,
  76671. connectedImpostor: connectedImpostor,
  76672. joint: joint
  76673. };
  76674. joint.physicsPlugin = this._physicsPlugin;
  76675. this._joints.push(impostorJoint);
  76676. this._physicsPlugin.generateJoint(impostorJoint);
  76677. };
  76678. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  76679. var matchingJoints = this._joints.filter(function (impostorJoint) {
  76680. return (impostorJoint.connectedImpostor === connectedImpostor
  76681. && impostorJoint.joint === joint
  76682. && impostorJoint.mainImpostor === mainImpostor);
  76683. });
  76684. if (matchingJoints.length) {
  76685. this._physicsPlugin.removeJoint(matchingJoints[0]);
  76686. //TODO remove it from the list as well
  76687. }
  76688. };
  76689. /**
  76690. * Called by the scene. no need to call it.
  76691. */
  76692. PhysicsEngine.prototype._step = function (delta) {
  76693. var _this = this;
  76694. //check if any mesh has no body / requires an update
  76695. this._impostors.forEach(function (impostor) {
  76696. if (impostor.isBodyInitRequired()) {
  76697. _this._physicsPlugin.generatePhysicsBody(impostor);
  76698. }
  76699. });
  76700. if (delta > 0.1) {
  76701. delta = 0.1;
  76702. }
  76703. else if (delta <= 0) {
  76704. delta = 1.0 / 60.0;
  76705. }
  76706. this._physicsPlugin.executeStep(delta, this._impostors);
  76707. };
  76708. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  76709. return this._physicsPlugin;
  76710. };
  76711. PhysicsEngine.prototype.getImpostors = function () {
  76712. return this._impostors;
  76713. };
  76714. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  76715. for (var i = 0; i < this._impostors.length; ++i) {
  76716. if (this._impostors[i].object === object) {
  76717. return this._impostors[i];
  76718. }
  76719. }
  76720. return null;
  76721. };
  76722. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  76723. for (var i = 0; i < this._impostors.length; ++i) {
  76724. if (this._impostors[i].physicsBody === body) {
  76725. return this._impostors[i];
  76726. }
  76727. }
  76728. return null;
  76729. };
  76730. // Statics
  76731. PhysicsEngine.Epsilon = 0.001;
  76732. return PhysicsEngine;
  76733. }());
  76734. BABYLON.PhysicsEngine = PhysicsEngine;
  76735. })(BABYLON || (BABYLON = {}));
  76736. //# sourceMappingURL=babylon.physicsEngine.js.map
  76737. var BABYLON;
  76738. (function (BABYLON) {
  76739. var PhysicsHelper = /** @class */ (function () {
  76740. function PhysicsHelper(scene) {
  76741. this._scene = scene;
  76742. this._physicsEngine = this._scene.getPhysicsEngine();
  76743. if (!this._physicsEngine) {
  76744. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  76745. }
  76746. }
  76747. /**
  76748. * @param {Vector3} origin the origin of the explosion
  76749. * @param {number} radius the explosion radius
  76750. * @param {number} strength the explosion strength
  76751. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76752. */
  76753. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  76754. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76755. if (!this._physicsEngine) {
  76756. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  76757. return null;
  76758. }
  76759. var impostors = this._physicsEngine.getImpostors();
  76760. if (impostors.length === 0) {
  76761. return null;
  76762. }
  76763. var event = new PhysicsRadialExplosionEvent(this._scene);
  76764. impostors.forEach(function (impostor) {
  76765. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76766. if (!impostorForceAndContactPoint) {
  76767. return;
  76768. }
  76769. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76770. });
  76771. event.dispose(false);
  76772. return event;
  76773. };
  76774. /**
  76775. * @param {Vector3} origin the origin of the explosion
  76776. * @param {number} radius the explosion radius
  76777. * @param {number} strength the explosion strength
  76778. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76779. */
  76780. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  76781. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76782. if (!this._physicsEngine) {
  76783. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76784. return null;
  76785. }
  76786. var impostors = this._physicsEngine.getImpostors();
  76787. if (impostors.length === 0) {
  76788. return null;
  76789. }
  76790. var event = new PhysicsRadialExplosionEvent(this._scene);
  76791. impostors.forEach(function (impostor) {
  76792. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76793. if (!impostorForceAndContactPoint) {
  76794. return;
  76795. }
  76796. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76797. });
  76798. event.dispose(false);
  76799. return event;
  76800. };
  76801. /**
  76802. * @param {Vector3} origin the origin of the explosion
  76803. * @param {number} radius the explosion radius
  76804. * @param {number} strength the explosion strength
  76805. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76806. */
  76807. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  76808. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76809. if (!this._physicsEngine) {
  76810. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76811. return null;
  76812. }
  76813. var impostors = this._physicsEngine.getImpostors();
  76814. if (impostors.length === 0) {
  76815. return null;
  76816. }
  76817. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  76818. event.dispose(false);
  76819. return event;
  76820. };
  76821. /**
  76822. * @param {Vector3} origin the origin of the updraft
  76823. * @param {number} radius the radius of the updraft
  76824. * @param {number} strength the strength of the updraft
  76825. * @param {number} height the height of the updraft
  76826. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  76827. */
  76828. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  76829. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  76830. if (!this._physicsEngine) {
  76831. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76832. return null;
  76833. }
  76834. if (this._physicsEngine.getImpostors().length === 0) {
  76835. return null;
  76836. }
  76837. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  76838. event.dispose(false);
  76839. return event;
  76840. };
  76841. /**
  76842. * @param {Vector3} origin the of the vortex
  76843. * @param {number} radius the radius of the vortex
  76844. * @param {number} strength the strength of the vortex
  76845. * @param {number} height the height of the vortex
  76846. */
  76847. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  76848. if (!this._physicsEngine) {
  76849. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76850. return null;
  76851. }
  76852. if (this._physicsEngine.getImpostors().length === 0) {
  76853. return null;
  76854. }
  76855. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  76856. event.dispose(false);
  76857. return event;
  76858. };
  76859. return PhysicsHelper;
  76860. }());
  76861. BABYLON.PhysicsHelper = PhysicsHelper;
  76862. /***** Radial explosion *****/
  76863. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  76864. function PhysicsRadialExplosionEvent(scene) {
  76865. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  76866. this._rays = [];
  76867. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  76868. this._scene = scene;
  76869. }
  76870. /**
  76871. * Returns the data related to the radial explosion event (sphere & rays).
  76872. * @returns {PhysicsRadialExplosionEventData}
  76873. */
  76874. PhysicsRadialExplosionEvent.prototype.getData = function () {
  76875. this._dataFetched = true;
  76876. return {
  76877. sphere: this._sphere,
  76878. rays: this._rays,
  76879. };
  76880. };
  76881. /**
  76882. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  76883. * @param impostor
  76884. * @param {Vector3} origin the origin of the explosion
  76885. * @param {number} radius the explosion radius
  76886. * @param {number} strength the explosion strength
  76887. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  76888. * @returns {Nullable<PhysicsForceAndContactPoint>}
  76889. */
  76890. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  76891. if (impostor.mass === 0) {
  76892. return null;
  76893. }
  76894. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  76895. return null;
  76896. }
  76897. if (impostor.object.getClassName() !== 'Mesh') {
  76898. return null;
  76899. }
  76900. var impostorObject = impostor.object;
  76901. var impostorObjectCenter = impostor.getObjectCenter();
  76902. var direction = impostorObjectCenter.subtract(origin);
  76903. var ray = new BABYLON.Ray(origin, direction, radius);
  76904. this._rays.push(ray);
  76905. var hit = ray.intersectsMesh(impostorObject);
  76906. var contactPoint = hit.pickedPoint;
  76907. if (!contactPoint) {
  76908. return null;
  76909. }
  76910. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  76911. if (distanceFromOrigin > radius) {
  76912. return null;
  76913. }
  76914. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  76915. ? strength
  76916. : strength * (1 - (distanceFromOrigin / radius));
  76917. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76918. return { force: force, contactPoint: contactPoint };
  76919. };
  76920. /**
  76921. * Disposes the sphere.
  76922. * @param {bolean} force
  76923. */
  76924. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  76925. var _this = this;
  76926. if (force === void 0) { force = true; }
  76927. if (force) {
  76928. this._sphere.dispose();
  76929. }
  76930. else {
  76931. setTimeout(function () {
  76932. if (!_this._dataFetched) {
  76933. _this._sphere.dispose();
  76934. }
  76935. }, 0);
  76936. }
  76937. };
  76938. /*** Helpers ***/
  76939. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  76940. if (!this._sphere) {
  76941. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  76942. this._sphere.isVisible = false;
  76943. }
  76944. };
  76945. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  76946. var impostorObject = impostor.object;
  76947. this._prepareSphere();
  76948. this._sphere.position = origin;
  76949. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  76950. this._sphere._updateBoundingInfo();
  76951. this._sphere.computeWorldMatrix(true);
  76952. return this._sphere.intersectsMesh(impostorObject, true);
  76953. };
  76954. return PhysicsRadialExplosionEvent;
  76955. }());
  76956. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  76957. /***** Gravitational Field *****/
  76958. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  76959. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  76960. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76961. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76962. this._physicsHelper = physicsHelper;
  76963. this._scene = scene;
  76964. this._origin = origin;
  76965. this._radius = radius;
  76966. this._strength = strength;
  76967. this._falloff = falloff;
  76968. this._tickCallback = this._tick.bind(this);
  76969. }
  76970. /**
  76971. * Returns the data related to the gravitational field event (sphere).
  76972. * @returns {PhysicsGravitationalFieldEventData}
  76973. */
  76974. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  76975. this._dataFetched = true;
  76976. return {
  76977. sphere: this._sphere,
  76978. };
  76979. };
  76980. /**
  76981. * Enables the gravitational field.
  76982. */
  76983. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  76984. this._tickCallback.call(this);
  76985. this._scene.registerBeforeRender(this._tickCallback);
  76986. };
  76987. /**
  76988. * Disables the gravitational field.
  76989. */
  76990. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  76991. this._scene.unregisterBeforeRender(this._tickCallback);
  76992. };
  76993. /**
  76994. * Disposes the sphere.
  76995. * @param {bolean} force
  76996. */
  76997. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  76998. var _this = this;
  76999. if (force === void 0) { force = true; }
  77000. if (force) {
  77001. this._sphere.dispose();
  77002. }
  77003. else {
  77004. setTimeout(function () {
  77005. if (!_this._dataFetched) {
  77006. _this._sphere.dispose();
  77007. }
  77008. }, 0);
  77009. }
  77010. };
  77011. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  77012. // Since the params won't change, we fetch the event only once
  77013. if (this._sphere) {
  77014. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77015. }
  77016. else {
  77017. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77018. if (radialExplosionEvent) {
  77019. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  77020. }
  77021. }
  77022. };
  77023. return PhysicsGravitationalFieldEvent;
  77024. }());
  77025. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  77026. /***** Updraft *****/
  77027. var PhysicsUpdraftEvent = /** @class */ (function () {
  77028. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  77029. this._scene = _scene;
  77030. this._origin = _origin;
  77031. this._radius = _radius;
  77032. this._strength = _strength;
  77033. this._height = _height;
  77034. this._updraftMode = _updraftMode;
  77035. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77036. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  77037. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77038. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77039. this._physicsEngine = this._scene.getPhysicsEngine();
  77040. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77041. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77042. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77043. this._originDirection = this._origin.subtract(this._originTop).normalize();
  77044. }
  77045. this._tickCallback = this._tick.bind(this);
  77046. }
  77047. /**
  77048. * Returns the data related to the updraft event (cylinder).
  77049. * @returns {PhysicsUpdraftEventData}
  77050. */
  77051. PhysicsUpdraftEvent.prototype.getData = function () {
  77052. this._dataFetched = true;
  77053. return {
  77054. cylinder: this._cylinder,
  77055. };
  77056. };
  77057. /**
  77058. * Enables the updraft.
  77059. */
  77060. PhysicsUpdraftEvent.prototype.enable = function () {
  77061. this._tickCallback.call(this);
  77062. this._scene.registerBeforeRender(this._tickCallback);
  77063. };
  77064. /**
  77065. * Disables the cortex.
  77066. */
  77067. PhysicsUpdraftEvent.prototype.disable = function () {
  77068. this._scene.unregisterBeforeRender(this._tickCallback);
  77069. };
  77070. /**
  77071. * Disposes the sphere.
  77072. * @param {bolean} force
  77073. */
  77074. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  77075. var _this = this;
  77076. if (force === void 0) { force = true; }
  77077. if (force) {
  77078. this._cylinder.dispose();
  77079. }
  77080. else {
  77081. setTimeout(function () {
  77082. if (!_this._dataFetched) {
  77083. _this._cylinder.dispose();
  77084. }
  77085. }, 0);
  77086. }
  77087. };
  77088. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77089. if (impostor.mass === 0) {
  77090. return null;
  77091. }
  77092. if (!this._intersectsWithCylinder(impostor)) {
  77093. return null;
  77094. }
  77095. var impostorObjectCenter = impostor.getObjectCenter();
  77096. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77097. var direction = this._originDirection;
  77098. }
  77099. else {
  77100. var direction = impostorObjectCenter.subtract(this._originTop);
  77101. }
  77102. var multiplier = this._strength * -1;
  77103. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77104. return { force: force, contactPoint: impostorObjectCenter };
  77105. };
  77106. PhysicsUpdraftEvent.prototype._tick = function () {
  77107. var _this = this;
  77108. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77109. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77110. if (!impostorForceAndContactPoint) {
  77111. return;
  77112. }
  77113. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77114. });
  77115. };
  77116. /*** Helpers ***/
  77117. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  77118. if (!this._cylinder) {
  77119. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  77120. height: this._height,
  77121. diameter: this._radius * 2,
  77122. }, this._scene);
  77123. this._cylinder.isVisible = false;
  77124. }
  77125. };
  77126. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  77127. var impostorObject = impostor.object;
  77128. this._prepareCylinder();
  77129. this._cylinder.position = this._cylinderPosition;
  77130. return this._cylinder.intersectsMesh(impostorObject, true);
  77131. };
  77132. return PhysicsUpdraftEvent;
  77133. }());
  77134. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  77135. /***** Vortex *****/
  77136. var PhysicsVortexEvent = /** @class */ (function () {
  77137. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  77138. this._scene = _scene;
  77139. this._origin = _origin;
  77140. this._radius = _radius;
  77141. this._strength = _strength;
  77142. this._height = _height;
  77143. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77144. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  77145. this._updraftMultiplier = 0.02;
  77146. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77147. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77148. this._physicsEngine = this._scene.getPhysicsEngine();
  77149. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77150. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77151. this._tickCallback = this._tick.bind(this);
  77152. }
  77153. /**
  77154. * Returns the data related to the vortex event (cylinder).
  77155. * @returns {PhysicsVortexEventData}
  77156. */
  77157. PhysicsVortexEvent.prototype.getData = function () {
  77158. this._dataFetched = true;
  77159. return {
  77160. cylinder: this._cylinder,
  77161. };
  77162. };
  77163. /**
  77164. * Enables the vortex.
  77165. */
  77166. PhysicsVortexEvent.prototype.enable = function () {
  77167. this._tickCallback.call(this);
  77168. this._scene.registerBeforeRender(this._tickCallback);
  77169. };
  77170. /**
  77171. * Disables the cortex.
  77172. */
  77173. PhysicsVortexEvent.prototype.disable = function () {
  77174. this._scene.unregisterBeforeRender(this._tickCallback);
  77175. };
  77176. /**
  77177. * Disposes the sphere.
  77178. * @param {bolean} force
  77179. */
  77180. PhysicsVortexEvent.prototype.dispose = function (force) {
  77181. var _this = this;
  77182. if (force === void 0) { force = true; }
  77183. if (force) {
  77184. this._cylinder.dispose();
  77185. }
  77186. else {
  77187. setTimeout(function () {
  77188. if (!_this._dataFetched) {
  77189. _this._cylinder.dispose();
  77190. }
  77191. }, 0);
  77192. }
  77193. };
  77194. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77195. if (impostor.mass === 0) {
  77196. return null;
  77197. }
  77198. if (!this._intersectsWithCylinder(impostor)) {
  77199. return null;
  77200. }
  77201. if (impostor.object.getClassName() !== 'Mesh') {
  77202. return null;
  77203. }
  77204. var impostorObject = impostor.object;
  77205. var impostorObjectCenter = impostor.getObjectCenter();
  77206. 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)
  77207. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  77208. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  77209. var hit = ray.intersectsMesh(impostorObject);
  77210. var contactPoint = hit.pickedPoint;
  77211. if (!contactPoint) {
  77212. return null;
  77213. }
  77214. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  77215. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  77216. var directionToOrigin = contactPoint.normalize();
  77217. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77218. directionToOrigin = directionToOrigin.negate();
  77219. }
  77220. // TODO: find a more physically based solution
  77221. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77222. var forceX = directionToOrigin.x * this._strength / 8;
  77223. var forceY = directionToOrigin.y * this._updraftMultiplier;
  77224. var forceZ = directionToOrigin.z * this._strength / 8;
  77225. }
  77226. else {
  77227. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  77228. var forceY = this._originTop.y * this._updraftMultiplier;
  77229. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  77230. }
  77231. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  77232. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  77233. return { force: force, contactPoint: impostorObjectCenter };
  77234. };
  77235. PhysicsVortexEvent.prototype._tick = function () {
  77236. var _this = this;
  77237. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77238. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77239. if (!impostorForceAndContactPoint) {
  77240. return;
  77241. }
  77242. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77243. });
  77244. };
  77245. /*** Helpers ***/
  77246. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  77247. if (!this._cylinder) {
  77248. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  77249. height: this._height,
  77250. diameter: this._radius * 2,
  77251. }, this._scene);
  77252. this._cylinder.isVisible = false;
  77253. }
  77254. };
  77255. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  77256. var impostorObject = impostor.object;
  77257. this._prepareCylinder();
  77258. this._cylinder.position = this._cylinderPosition;
  77259. return this._cylinder.intersectsMesh(impostorObject, true);
  77260. };
  77261. return PhysicsVortexEvent;
  77262. }());
  77263. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  77264. /***** Enums *****/
  77265. /**
  77266. * The strenght of the force in correspondence to the distance of the affected object
  77267. */
  77268. var PhysicsRadialImpulseFalloff;
  77269. (function (PhysicsRadialImpulseFalloff) {
  77270. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  77271. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  77272. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  77273. /**
  77274. * The strenght of the force in correspondence to the distance of the affected object
  77275. */
  77276. var PhysicsUpdraftMode;
  77277. (function (PhysicsUpdraftMode) {
  77278. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  77279. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  77280. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  77281. })(BABYLON || (BABYLON = {}));
  77282. //# sourceMappingURL=babylon.physicsHelper.js.map
  77283. var BABYLON;
  77284. (function (BABYLON) {
  77285. var CannonJSPlugin = /** @class */ (function () {
  77286. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  77287. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  77288. if (iterations === void 0) { iterations = 10; }
  77289. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  77290. this.name = "CannonJSPlugin";
  77291. this._physicsMaterials = new Array();
  77292. this._fixedTimeStep = 1 / 60;
  77293. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  77294. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  77295. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  77296. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  77297. this._tmpPosition = BABYLON.Vector3.Zero();
  77298. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  77299. this._tmpUnityRotation = new BABYLON.Quaternion();
  77300. if (!this.isSupported()) {
  77301. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  77302. return;
  77303. }
  77304. this._extendNamespace();
  77305. this.world = new this.BJSCANNON.World();
  77306. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  77307. this.world.solver.iterations = iterations;
  77308. }
  77309. CannonJSPlugin.prototype.setGravity = function (gravity) {
  77310. this.world.gravity.copy(gravity);
  77311. };
  77312. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  77313. this._fixedTimeStep = timeStep;
  77314. };
  77315. CannonJSPlugin.prototype.getTimeStep = function () {
  77316. return this._fixedTimeStep;
  77317. };
  77318. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  77319. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  77320. };
  77321. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77322. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77323. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77324. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  77325. };
  77326. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77327. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77328. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77329. impostor.physicsBody.applyForce(impulse, worldPoint);
  77330. };
  77331. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77332. //parent-child relationship. Does this impostor has a parent impostor?
  77333. if (impostor.parent) {
  77334. if (impostor.physicsBody) {
  77335. this.removePhysicsBody(impostor);
  77336. //TODO is that needed?
  77337. impostor.forceUpdate();
  77338. }
  77339. return;
  77340. }
  77341. //should a new body be created for this impostor?
  77342. if (impostor.isBodyInitRequired()) {
  77343. var shape = this._createShape(impostor);
  77344. //unregister events, if body is being changed
  77345. var oldBody = impostor.physicsBody;
  77346. if (oldBody) {
  77347. this.removePhysicsBody(impostor);
  77348. }
  77349. //create the body and material
  77350. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  77351. var bodyCreationObject = {
  77352. mass: impostor.getParam("mass"),
  77353. material: material
  77354. };
  77355. // A simple extend, in case native options were used.
  77356. var nativeOptions = impostor.getParam("nativeOptions");
  77357. for (var key in nativeOptions) {
  77358. if (nativeOptions.hasOwnProperty(key)) {
  77359. bodyCreationObject[key] = nativeOptions[key];
  77360. }
  77361. }
  77362. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  77363. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  77364. this.world.addEventListener("preStep", impostor.beforeStep);
  77365. this.world.addEventListener("postStep", impostor.afterStep);
  77366. impostor.physicsBody.addShape(shape);
  77367. this.world.add(impostor.physicsBody);
  77368. //try to keep the body moving in the right direction by taking old properties.
  77369. //Should be tested!
  77370. if (oldBody) {
  77371. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  77372. impostor.physicsBody[param].copy(oldBody[param]);
  77373. });
  77374. }
  77375. this._processChildMeshes(impostor);
  77376. }
  77377. //now update the body's transformation
  77378. this._updatePhysicsBodyTransformation(impostor);
  77379. };
  77380. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  77381. var _this = this;
  77382. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  77383. var currentRotation = mainImpostor.object.rotationQuaternion;
  77384. if (meshChildren.length) {
  77385. var processMesh = function (localPosition, mesh) {
  77386. if (!currentRotation || !mesh.rotationQuaternion) {
  77387. return;
  77388. }
  77389. var childImpostor = mesh.getPhysicsImpostor();
  77390. if (childImpostor) {
  77391. var parent = childImpostor.parent;
  77392. if (parent !== mainImpostor) {
  77393. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  77394. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  77395. if (childImpostor.physicsBody) {
  77396. _this.removePhysicsBody(childImpostor);
  77397. childImpostor.physicsBody = null;
  77398. }
  77399. childImpostor.parent = mainImpostor;
  77400. childImpostor.resetUpdateFlags();
  77401. 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));
  77402. //Add the mass of the children.
  77403. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  77404. }
  77405. }
  77406. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  77407. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  77408. };
  77409. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  77410. }
  77411. };
  77412. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77413. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  77414. this.world.removeEventListener("preStep", impostor.beforeStep);
  77415. this.world.removeEventListener("postStep", impostor.afterStep);
  77416. this.world.remove(impostor.physicsBody);
  77417. };
  77418. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77419. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77420. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77421. if (!mainBody || !connectedBody) {
  77422. return;
  77423. }
  77424. var constraint;
  77425. var jointData = impostorJoint.joint.jointData;
  77426. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  77427. var constraintData = {
  77428. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  77429. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  77430. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  77431. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  77432. maxForce: jointData.nativeParams.maxForce,
  77433. collideConnected: !!jointData.collision
  77434. };
  77435. switch (impostorJoint.joint.type) {
  77436. case BABYLON.PhysicsJoint.HingeJoint:
  77437. case BABYLON.PhysicsJoint.Hinge2Joint:
  77438. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  77439. break;
  77440. case BABYLON.PhysicsJoint.DistanceJoint:
  77441. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  77442. break;
  77443. case BABYLON.PhysicsJoint.SpringJoint:
  77444. var springData = jointData;
  77445. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  77446. restLength: springData.length,
  77447. stiffness: springData.stiffness,
  77448. damping: springData.damping,
  77449. localAnchorA: constraintData.pivotA,
  77450. localAnchorB: constraintData.pivotB
  77451. });
  77452. break;
  77453. case BABYLON.PhysicsJoint.LockJoint:
  77454. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  77455. break;
  77456. case BABYLON.PhysicsJoint.PointToPointJoint:
  77457. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77458. default:
  77459. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  77460. break;
  77461. }
  77462. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  77463. constraint.collideConnected = !!jointData.collision;
  77464. impostorJoint.joint.physicsJoint = constraint;
  77465. //don't add spring as constraint, as it is not one.
  77466. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  77467. this.world.addConstraint(constraint);
  77468. }
  77469. else {
  77470. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  77471. constraint.applyForce();
  77472. });
  77473. }
  77474. };
  77475. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77476. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  77477. };
  77478. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  77479. var index;
  77480. var mat;
  77481. for (index = 0; index < this._physicsMaterials.length; index++) {
  77482. mat = this._physicsMaterials[index];
  77483. if (mat.friction === friction && mat.restitution === restitution) {
  77484. return mat;
  77485. }
  77486. }
  77487. var currentMat = new this.BJSCANNON.Material(name);
  77488. currentMat.friction = friction;
  77489. currentMat.restitution = restitution;
  77490. this._physicsMaterials.push(currentMat);
  77491. return currentMat;
  77492. };
  77493. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  77494. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  77495. };
  77496. CannonJSPlugin.prototype._createShape = function (impostor) {
  77497. var object = impostor.object;
  77498. var returnValue;
  77499. var extendSize = impostor.getObjectExtendSize();
  77500. switch (impostor.type) {
  77501. case BABYLON.PhysicsImpostor.SphereImpostor:
  77502. var radiusX = extendSize.x;
  77503. var radiusY = extendSize.y;
  77504. var radiusZ = extendSize.z;
  77505. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  77506. break;
  77507. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  77508. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77509. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  77510. break;
  77511. case BABYLON.PhysicsImpostor.BoxImpostor:
  77512. var box = extendSize.scale(0.5);
  77513. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  77514. break;
  77515. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77516. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  77517. returnValue = new this.BJSCANNON.Plane();
  77518. break;
  77519. case BABYLON.PhysicsImpostor.MeshImpostor:
  77520. // should transform the vertex data to world coordinates!!
  77521. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  77522. var rawFaces = object.getIndices ? object.getIndices() : [];
  77523. if (!rawVerts)
  77524. return;
  77525. // get only scale! so the object could transform correctly.
  77526. var oldPosition = object.position.clone();
  77527. var oldRotation = object.rotation && object.rotation.clone();
  77528. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  77529. object.position.copyFromFloats(0, 0, 0);
  77530. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77531. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77532. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77533. var transform = object.computeWorldMatrix(true);
  77534. // convert rawVerts to object space
  77535. var temp = new Array();
  77536. var index;
  77537. for (index = 0; index < rawVerts.length; index += 3) {
  77538. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  77539. }
  77540. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  77541. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  77542. //now set back the transformation!
  77543. object.position.copyFrom(oldPosition);
  77544. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  77545. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  77546. break;
  77547. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  77548. var oldPosition2 = object.position.clone();
  77549. var oldRotation2 = object.rotation && object.rotation.clone();
  77550. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  77551. object.position.copyFromFloats(0, 0, 0);
  77552. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77553. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77554. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77555. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  77556. returnValue = this._createHeightmap(object);
  77557. object.position.copyFrom(oldPosition2);
  77558. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  77559. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  77560. object.computeWorldMatrix(true);
  77561. break;
  77562. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77563. returnValue = new this.BJSCANNON.Particle();
  77564. break;
  77565. }
  77566. return returnValue;
  77567. };
  77568. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  77569. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77570. var transform = object.computeWorldMatrix(true);
  77571. // convert rawVerts to object space
  77572. var temp = new Array();
  77573. var index;
  77574. for (index = 0; index < pos.length; index += 3) {
  77575. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  77576. }
  77577. pos = temp;
  77578. var matrix = new Array();
  77579. //For now pointDepth will not be used and will be automatically calculated.
  77580. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  77581. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  77582. var boundingInfo = object.getBoundingInfo();
  77583. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  77584. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  77585. var elementSize = dim * 2 / arraySize;
  77586. for (var i = 0; i < pos.length; i = i + 3) {
  77587. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  77588. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  77589. var y = -pos[i + 2] + minY;
  77590. if (!matrix[x]) {
  77591. matrix[x] = [];
  77592. }
  77593. if (!matrix[x][z]) {
  77594. matrix[x][z] = y;
  77595. }
  77596. matrix[x][z] = Math.max(y, matrix[x][z]);
  77597. }
  77598. for (var x = 0; x <= arraySize; ++x) {
  77599. if (!matrix[x]) {
  77600. var loc = 1;
  77601. while (!matrix[(x + loc) % arraySize]) {
  77602. loc++;
  77603. }
  77604. matrix[x] = matrix[(x + loc) % arraySize].slice();
  77605. //console.log("missing x", x);
  77606. }
  77607. for (var z = 0; z <= arraySize; ++z) {
  77608. if (!matrix[x][z]) {
  77609. var loc = 1;
  77610. var newValue;
  77611. while (newValue === undefined) {
  77612. newValue = matrix[x][(z + loc++) % arraySize];
  77613. }
  77614. matrix[x][z] = newValue;
  77615. }
  77616. }
  77617. }
  77618. var shape = new this.BJSCANNON.Heightfield(matrix, {
  77619. elementSize: elementSize
  77620. });
  77621. //For future reference, needed for body transformation
  77622. shape.minY = minY;
  77623. return shape;
  77624. };
  77625. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  77626. var object = impostor.object;
  77627. //make sure it is updated...
  77628. object.computeWorldMatrix && object.computeWorldMatrix(true);
  77629. // The delta between the mesh position and the mesh bounding box center
  77630. var bInfo = object.getBoundingInfo();
  77631. if (!bInfo)
  77632. return;
  77633. var center = impostor.getObjectCenter();
  77634. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  77635. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  77636. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  77637. this._tmpPosition.copyFrom(center);
  77638. var quaternion = object.rotationQuaternion;
  77639. if (!quaternion) {
  77640. return;
  77641. }
  77642. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  77643. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  77644. //-90 DEG in X, precalculated
  77645. quaternion = quaternion.multiply(this._minus90X);
  77646. //Invert! (Precalculated, 90 deg in X)
  77647. //No need to clone. this will never change.
  77648. impostor.setDeltaRotation(this._plus90X);
  77649. }
  77650. //If it is a heightfield, if should be centered.
  77651. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  77652. var mesh = object;
  77653. var boundingInfo = mesh.getBoundingInfo();
  77654. //calculate the correct body position:
  77655. var rotationQuaternion = mesh.rotationQuaternion;
  77656. mesh.rotationQuaternion = this._tmpUnityRotation;
  77657. mesh.computeWorldMatrix(true);
  77658. //get original center with no rotation
  77659. var c = center.clone();
  77660. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  77661. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  77662. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  77663. mesh.setPreTransformMatrix(p);
  77664. mesh.computeWorldMatrix(true);
  77665. //calculate the translation
  77666. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  77667. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  77668. //add it inverted to the delta
  77669. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  77670. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  77671. //rotation is back
  77672. mesh.rotationQuaternion = rotationQuaternion;
  77673. mesh.setPreTransformMatrix(oldPivot);
  77674. mesh.computeWorldMatrix(true);
  77675. }
  77676. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  77677. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  77678. //this._tmpPosition.copyFrom(object.position);
  77679. }
  77680. impostor.setDeltaPosition(this._tmpDeltaPosition);
  77681. //Now update the impostor object
  77682. impostor.physicsBody.position.copy(this._tmpPosition);
  77683. impostor.physicsBody.quaternion.copy(quaternion);
  77684. };
  77685. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77686. impostor.object.position.copyFrom(impostor.physicsBody.position);
  77687. if (impostor.object.rotationQuaternion) {
  77688. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  77689. }
  77690. };
  77691. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77692. impostor.physicsBody.position.copy(newPosition);
  77693. impostor.physicsBody.quaternion.copy(newRotation);
  77694. };
  77695. CannonJSPlugin.prototype.isSupported = function () {
  77696. return this.BJSCANNON !== undefined;
  77697. };
  77698. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77699. impostor.physicsBody.velocity.copy(velocity);
  77700. };
  77701. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77702. impostor.physicsBody.angularVelocity.copy(velocity);
  77703. };
  77704. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77705. var v = impostor.physicsBody.velocity;
  77706. if (!v) {
  77707. return null;
  77708. }
  77709. return new BABYLON.Vector3(v.x, v.y, v.z);
  77710. };
  77711. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77712. var v = impostor.physicsBody.angularVelocity;
  77713. if (!v) {
  77714. return null;
  77715. }
  77716. return new BABYLON.Vector3(v.x, v.y, v.z);
  77717. };
  77718. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77719. impostor.physicsBody.mass = mass;
  77720. impostor.physicsBody.updateMassProperties();
  77721. };
  77722. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  77723. return impostor.physicsBody.mass;
  77724. };
  77725. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  77726. return impostor.physicsBody.material.friction;
  77727. };
  77728. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77729. impostor.physicsBody.material.friction = friction;
  77730. };
  77731. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77732. return impostor.physicsBody.material.restitution;
  77733. };
  77734. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77735. impostor.physicsBody.material.restitution = restitution;
  77736. };
  77737. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  77738. impostor.physicsBody.sleep();
  77739. };
  77740. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  77741. impostor.physicsBody.wakeUp();
  77742. };
  77743. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77744. joint.physicsJoint.distance = maxDistance;
  77745. };
  77746. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77747. // if (!motorIndex) {
  77748. // joint.physicsJoint.enableMotor();
  77749. // }
  77750. // }
  77751. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77752. // if (!motorIndex) {
  77753. // joint.physicsJoint.disableMotor();
  77754. // }
  77755. // }
  77756. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77757. if (!motorIndex) {
  77758. joint.physicsJoint.enableMotor();
  77759. joint.physicsJoint.setMotorSpeed(speed);
  77760. if (maxForce) {
  77761. this.setLimit(joint, maxForce);
  77762. }
  77763. }
  77764. };
  77765. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  77766. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  77767. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  77768. };
  77769. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77770. var body = impostor.physicsBody;
  77771. mesh.position.x = body.position.x;
  77772. mesh.position.y = body.position.y;
  77773. mesh.position.z = body.position.z;
  77774. if (mesh.rotationQuaternion) {
  77775. mesh.rotationQuaternion.x = body.quaternion.x;
  77776. mesh.rotationQuaternion.y = body.quaternion.y;
  77777. mesh.rotationQuaternion.z = body.quaternion.z;
  77778. mesh.rotationQuaternion.w = body.quaternion.w;
  77779. }
  77780. };
  77781. CannonJSPlugin.prototype.getRadius = function (impostor) {
  77782. var shape = impostor.physicsBody.shapes[0];
  77783. return shape.boundingSphereRadius;
  77784. };
  77785. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77786. var shape = impostor.physicsBody.shapes[0];
  77787. result.x = shape.halfExtents.x * 2;
  77788. result.y = shape.halfExtents.y * 2;
  77789. result.z = shape.halfExtents.z * 2;
  77790. };
  77791. CannonJSPlugin.prototype.dispose = function () {
  77792. };
  77793. CannonJSPlugin.prototype._extendNamespace = function () {
  77794. //this will force cannon to execute at least one step when using interpolation
  77795. var step_tmp1 = new this.BJSCANNON.Vec3();
  77796. var Engine = this.BJSCANNON;
  77797. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  77798. maxSubSteps = maxSubSteps || 10;
  77799. timeSinceLastCalled = timeSinceLastCalled || 0;
  77800. if (timeSinceLastCalled === 0) {
  77801. this.internalStep(dt);
  77802. this.time += dt;
  77803. }
  77804. else {
  77805. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  77806. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  77807. var t0 = performance.now();
  77808. for (var i = 0; i !== internalSteps; i++) {
  77809. this.internalStep(dt);
  77810. if (performance.now() - t0 > dt * 1000) {
  77811. break;
  77812. }
  77813. }
  77814. this.time += timeSinceLastCalled;
  77815. var h = this.time % dt;
  77816. var h_div_dt = h / dt;
  77817. var interpvelo = step_tmp1;
  77818. var bodies = this.bodies;
  77819. for (var j = 0; j !== bodies.length; j++) {
  77820. var b = bodies[j];
  77821. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  77822. b.position.vsub(b.previousPosition, interpvelo);
  77823. interpvelo.scale(h_div_dt, interpvelo);
  77824. b.position.vadd(interpvelo, b.interpolatedPosition);
  77825. }
  77826. else {
  77827. b.interpolatedPosition.copy(b.position);
  77828. b.interpolatedQuaternion.copy(b.quaternion);
  77829. }
  77830. }
  77831. }
  77832. };
  77833. };
  77834. return CannonJSPlugin;
  77835. }());
  77836. BABYLON.CannonJSPlugin = CannonJSPlugin;
  77837. })(BABYLON || (BABYLON = {}));
  77838. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  77839. var BABYLON;
  77840. (function (BABYLON) {
  77841. var OimoJSPlugin = /** @class */ (function () {
  77842. function OimoJSPlugin(iterations) {
  77843. this.name = "OimoJSPlugin";
  77844. this._tmpImpostorsArray = [];
  77845. this._tmpPositionVector = BABYLON.Vector3.Zero();
  77846. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  77847. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  77848. this.world.worldscale(1);
  77849. this.world.clear();
  77850. //making sure no stats are calculated
  77851. this.world.isNoStat = true;
  77852. }
  77853. OimoJSPlugin.prototype.setGravity = function (gravity) {
  77854. this.world.gravity.copy(gravity);
  77855. };
  77856. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  77857. this.world.timeStep = timeStep;
  77858. };
  77859. OimoJSPlugin.prototype.getTimeStep = function () {
  77860. return this.world.timeStep;
  77861. };
  77862. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  77863. var _this = this;
  77864. impostors.forEach(function (impostor) {
  77865. impostor.beforeStep();
  77866. });
  77867. this.world.step();
  77868. impostors.forEach(function (impostor) {
  77869. impostor.afterStep();
  77870. //update the ordered impostors array
  77871. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  77872. });
  77873. //check for collisions
  77874. var contact = this.world.contacts;
  77875. while (contact !== null) {
  77876. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  77877. contact = contact.next;
  77878. continue;
  77879. }
  77880. //is this body colliding with any other? get the impostor
  77881. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  77882. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  77883. if (!mainImpostor || !collidingImpostor) {
  77884. contact = contact.next;
  77885. continue;
  77886. }
  77887. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  77888. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  77889. contact = contact.next;
  77890. }
  77891. };
  77892. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77893. var mass = impostor.physicsBody.massInfo.mass;
  77894. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  77895. };
  77896. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77897. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  77898. this.applyImpulse(impostor, force, contactPoint);
  77899. };
  77900. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77901. var _this = this;
  77902. //parent-child relationship. Does this impostor has a parent impostor?
  77903. if (impostor.parent) {
  77904. if (impostor.physicsBody) {
  77905. this.removePhysicsBody(impostor);
  77906. //TODO is that needed?
  77907. impostor.forceUpdate();
  77908. }
  77909. return;
  77910. }
  77911. if (impostor.isBodyInitRequired()) {
  77912. var bodyConfig = {
  77913. name: impostor.uniqueId,
  77914. //Oimo must have mass, also for static objects.
  77915. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  77916. size: [],
  77917. type: [],
  77918. pos: [],
  77919. rot: [],
  77920. move: impostor.getParam("mass") !== 0,
  77921. //Supporting older versions of Oimo
  77922. world: this.world
  77923. };
  77924. var impostors = [impostor];
  77925. var addToArray = function (parent) {
  77926. if (!parent.getChildMeshes)
  77927. return;
  77928. parent.getChildMeshes().forEach(function (m) {
  77929. if (m.physicsImpostor) {
  77930. impostors.push(m.physicsImpostor);
  77931. //m.physicsImpostor._init();
  77932. }
  77933. });
  77934. };
  77935. addToArray(impostor.object);
  77936. var checkWithEpsilon_1 = function (value) {
  77937. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  77938. };
  77939. impostors.forEach(function (i) {
  77940. if (!impostor.object.rotationQuaternion) {
  77941. return;
  77942. }
  77943. //get the correct bounding box
  77944. var oldQuaternion = i.object.rotationQuaternion;
  77945. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  77946. x: impostor.object.rotationQuaternion.x,
  77947. y: impostor.object.rotationQuaternion.y,
  77948. z: impostor.object.rotationQuaternion.z,
  77949. s: impostor.object.rotationQuaternion.w
  77950. });
  77951. var extendSize = i.getObjectExtendSize();
  77952. if (i === impostor) {
  77953. var center = impostor.getObjectCenter();
  77954. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  77955. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  77956. //Can also use Array.prototype.push.apply
  77957. bodyConfig.pos.push(center.x);
  77958. bodyConfig.pos.push(center.y);
  77959. bodyConfig.pos.push(center.z);
  77960. //tmp solution
  77961. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77962. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77963. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77964. }
  77965. else {
  77966. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  77967. bodyConfig.pos.push(localPosition.x);
  77968. bodyConfig.pos.push(localPosition.y);
  77969. bodyConfig.pos.push(localPosition.z);
  77970. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  77971. bodyConfig.rot.push(0);
  77972. bodyConfig.rot.push(0);
  77973. bodyConfig.rot.push(0);
  77974. }
  77975. // register mesh
  77976. switch (i.type) {
  77977. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77978. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  77979. case BABYLON.PhysicsImpostor.SphereImpostor:
  77980. var radiusX = extendSize.x;
  77981. var radiusY = extendSize.y;
  77982. var radiusZ = extendSize.z;
  77983. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  77984. bodyConfig.type.push('sphere');
  77985. //due to the way oimo works with compounds, add 3 times
  77986. bodyConfig.size.push(size);
  77987. bodyConfig.size.push(size);
  77988. bodyConfig.size.push(size);
  77989. break;
  77990. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77991. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  77992. var sizeY = checkWithEpsilon_1(extendSize.y);
  77993. bodyConfig.type.push('cylinder');
  77994. bodyConfig.size.push(sizeX);
  77995. bodyConfig.size.push(sizeY);
  77996. //due to the way oimo works with compounds, add one more value.
  77997. bodyConfig.size.push(sizeY);
  77998. break;
  77999. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78000. case BABYLON.PhysicsImpostor.BoxImpostor:
  78001. default:
  78002. var sizeX = checkWithEpsilon_1(extendSize.x);
  78003. var sizeY = checkWithEpsilon_1(extendSize.y);
  78004. var sizeZ = checkWithEpsilon_1(extendSize.z);
  78005. bodyConfig.type.push('box');
  78006. bodyConfig.size.push(sizeX);
  78007. bodyConfig.size.push(sizeY);
  78008. bodyConfig.size.push(sizeZ);
  78009. break;
  78010. }
  78011. //actually not needed, but hey...
  78012. i.object.rotationQuaternion = oldQuaternion;
  78013. });
  78014. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  78015. }
  78016. else {
  78017. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  78018. }
  78019. impostor.setDeltaPosition(this._tmpPositionVector);
  78020. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  78021. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  78022. };
  78023. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78024. //impostor.physicsBody.dispose();
  78025. //Same as : (older oimo versions)
  78026. this.world.removeRigidBody(impostor.physicsBody);
  78027. };
  78028. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78029. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78030. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78031. if (!mainBody || !connectedBody) {
  78032. return;
  78033. }
  78034. var jointData = impostorJoint.joint.jointData;
  78035. var options = jointData.nativeParams || {};
  78036. var type;
  78037. var nativeJointData = {
  78038. body1: mainBody,
  78039. body2: connectedBody,
  78040. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  78041. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  78042. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  78043. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  78044. min: options.min,
  78045. max: options.max,
  78046. collision: options.collision || jointData.collision,
  78047. spring: options.spring,
  78048. //supporting older version of Oimo
  78049. world: this.world
  78050. };
  78051. switch (impostorJoint.joint.type) {
  78052. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78053. type = "jointBall";
  78054. break;
  78055. case BABYLON.PhysicsJoint.SpringJoint:
  78056. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  78057. var springData = jointData;
  78058. nativeJointData.min = springData.length || nativeJointData.min;
  78059. //Max should also be set, just make sure it is at least min
  78060. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  78061. case BABYLON.PhysicsJoint.DistanceJoint:
  78062. type = "jointDistance";
  78063. nativeJointData.max = jointData.maxDistance;
  78064. break;
  78065. case BABYLON.PhysicsJoint.PrismaticJoint:
  78066. type = "jointPrisme";
  78067. break;
  78068. case BABYLON.PhysicsJoint.SliderJoint:
  78069. type = "jointSlide";
  78070. break;
  78071. case BABYLON.PhysicsJoint.WheelJoint:
  78072. type = "jointWheel";
  78073. break;
  78074. case BABYLON.PhysicsJoint.HingeJoint:
  78075. default:
  78076. type = "jointHinge";
  78077. break;
  78078. }
  78079. nativeJointData.type = type;
  78080. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  78081. };
  78082. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78083. //Bug in Oimo prevents us from disposing a joint in the playground
  78084. //joint.joint.physicsJoint.dispose();
  78085. //So we will bruteforce it!
  78086. try {
  78087. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  78088. }
  78089. catch (e) {
  78090. BABYLON.Tools.Warn(e);
  78091. }
  78092. };
  78093. OimoJSPlugin.prototype.isSupported = function () {
  78094. return this.BJSOIMO !== undefined;
  78095. };
  78096. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78097. if (!impostor.physicsBody.sleeping) {
  78098. //TODO check that
  78099. if (impostor.physicsBody.shapes.next) {
  78100. var parentShape = this._getLastShape(impostor.physicsBody);
  78101. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  78102. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  78103. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  78104. }
  78105. else {
  78106. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  78107. }
  78108. if (impostor.object.rotationQuaternion) {
  78109. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  78110. impostor.object.rotationQuaternion.normalize();
  78111. }
  78112. }
  78113. };
  78114. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78115. var body = impostor.physicsBody;
  78116. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  78117. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  78118. body.syncShapes();
  78119. body.awake();
  78120. };
  78121. OimoJSPlugin.prototype._getLastShape = function (body) {
  78122. var lastShape = body.shapes;
  78123. while (lastShape.next) {
  78124. lastShape = lastShape.next;
  78125. }
  78126. return lastShape;
  78127. };
  78128. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78129. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  78130. };
  78131. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78132. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  78133. };
  78134. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78135. var v = impostor.physicsBody.linearVelocity;
  78136. if (!v) {
  78137. return null;
  78138. }
  78139. return new BABYLON.Vector3(v.x, v.y, v.z);
  78140. };
  78141. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78142. var v = impostor.physicsBody.angularVelocity;
  78143. if (!v) {
  78144. return null;
  78145. }
  78146. return new BABYLON.Vector3(v.x, v.y, v.z);
  78147. };
  78148. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78149. var staticBody = mass === 0;
  78150. //this will actually set the body's density and not its mass.
  78151. //But this is how oimo treats the mass variable.
  78152. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  78153. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  78154. };
  78155. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  78156. return impostor.physicsBody.shapes.density;
  78157. };
  78158. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  78159. return impostor.physicsBody.shapes.friction;
  78160. };
  78161. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78162. impostor.physicsBody.shapes.friction = friction;
  78163. };
  78164. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78165. return impostor.physicsBody.shapes.restitution;
  78166. };
  78167. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78168. impostor.physicsBody.shapes.restitution = restitution;
  78169. };
  78170. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  78171. impostor.physicsBody.sleep();
  78172. };
  78173. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  78174. impostor.physicsBody.awake();
  78175. };
  78176. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78177. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  78178. if (minDistance !== void 0) {
  78179. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  78180. }
  78181. };
  78182. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78183. //TODO separate rotational and transational motors.
  78184. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78185. if (motor) {
  78186. motor.setMotor(speed, maxForce);
  78187. }
  78188. };
  78189. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  78190. //TODO separate rotational and transational motors.
  78191. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78192. if (motor) {
  78193. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  78194. }
  78195. };
  78196. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78197. var body = impostor.physicsBody;
  78198. mesh.position.x = body.position.x;
  78199. mesh.position.y = body.position.y;
  78200. mesh.position.z = body.position.z;
  78201. if (mesh.rotationQuaternion) {
  78202. mesh.rotationQuaternion.x = body.orientation.x;
  78203. mesh.rotationQuaternion.y = body.orientation.y;
  78204. mesh.rotationQuaternion.z = body.orientation.z;
  78205. mesh.rotationQuaternion.w = body.orientation.s;
  78206. }
  78207. };
  78208. OimoJSPlugin.prototype.getRadius = function (impostor) {
  78209. return impostor.physicsBody.shapes.radius;
  78210. };
  78211. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78212. var shape = impostor.physicsBody.shapes;
  78213. result.x = shape.halfWidth * 2;
  78214. result.y = shape.halfHeight * 2;
  78215. result.z = shape.halfDepth * 2;
  78216. };
  78217. OimoJSPlugin.prototype.dispose = function () {
  78218. this.world.clear();
  78219. };
  78220. return OimoJSPlugin;
  78221. }());
  78222. BABYLON.OimoJSPlugin = OimoJSPlugin;
  78223. })(BABYLON || (BABYLON = {}));
  78224. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  78225. var BABYLON;
  78226. (function (BABYLON) {
  78227. /*
  78228. * Based on jsTGALoader - Javascript loader for TGA file
  78229. * By Vincent Thibault
  78230. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  78231. */
  78232. var TGATools = /** @class */ (function () {
  78233. function TGATools() {
  78234. }
  78235. TGATools.GetTGAHeader = function (data) {
  78236. var offset = 0;
  78237. var header = {
  78238. id_length: data[offset++],
  78239. colormap_type: data[offset++],
  78240. image_type: data[offset++],
  78241. colormap_index: data[offset++] | data[offset++] << 8,
  78242. colormap_length: data[offset++] | data[offset++] << 8,
  78243. colormap_size: data[offset++],
  78244. origin: [
  78245. data[offset++] | data[offset++] << 8,
  78246. data[offset++] | data[offset++] << 8
  78247. ],
  78248. width: data[offset++] | data[offset++] << 8,
  78249. height: data[offset++] | data[offset++] << 8,
  78250. pixel_size: data[offset++],
  78251. flags: data[offset++]
  78252. };
  78253. return header;
  78254. };
  78255. TGATools.UploadContent = function (gl, data) {
  78256. // Not enough data to contain header ?
  78257. if (data.length < 19) {
  78258. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  78259. return;
  78260. }
  78261. // Read Header
  78262. var offset = 18;
  78263. var header = TGATools.GetTGAHeader(data);
  78264. // Assume it's a valid Targa file.
  78265. if (header.id_length + offset > data.length) {
  78266. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  78267. return;
  78268. }
  78269. // Skip not needed data
  78270. offset += header.id_length;
  78271. var use_rle = false;
  78272. var use_pal = false;
  78273. var use_grey = false;
  78274. // Get some informations.
  78275. switch (header.image_type) {
  78276. case TGATools._TYPE_RLE_INDEXED:
  78277. use_rle = true;
  78278. case TGATools._TYPE_INDEXED:
  78279. use_pal = true;
  78280. break;
  78281. case TGATools._TYPE_RLE_RGB:
  78282. use_rle = true;
  78283. case TGATools._TYPE_RGB:
  78284. // use_rgb = true;
  78285. break;
  78286. case TGATools._TYPE_RLE_GREY:
  78287. use_rle = true;
  78288. case TGATools._TYPE_GREY:
  78289. use_grey = true;
  78290. break;
  78291. }
  78292. var pixel_data;
  78293. // var numAlphaBits = header.flags & 0xf;
  78294. var pixel_size = header.pixel_size >> 3;
  78295. var pixel_total = header.width * header.height * pixel_size;
  78296. // Read palettes
  78297. var palettes;
  78298. if (use_pal) {
  78299. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  78300. }
  78301. // Read LRE
  78302. if (use_rle) {
  78303. pixel_data = new Uint8Array(pixel_total);
  78304. var c, count, i;
  78305. var localOffset = 0;
  78306. var pixels = new Uint8Array(pixel_size);
  78307. while (offset < pixel_total && localOffset < pixel_total) {
  78308. c = data[offset++];
  78309. count = (c & 0x7f) + 1;
  78310. // RLE pixels
  78311. if (c & 0x80) {
  78312. // Bind pixel tmp array
  78313. for (i = 0; i < pixel_size; ++i) {
  78314. pixels[i] = data[offset++];
  78315. }
  78316. // Copy pixel array
  78317. for (i = 0; i < count; ++i) {
  78318. pixel_data.set(pixels, localOffset + i * pixel_size);
  78319. }
  78320. localOffset += pixel_size * count;
  78321. }
  78322. else {
  78323. count *= pixel_size;
  78324. for (i = 0; i < count; ++i) {
  78325. pixel_data[localOffset + i] = data[offset++];
  78326. }
  78327. localOffset += count;
  78328. }
  78329. }
  78330. }
  78331. else {
  78332. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  78333. }
  78334. // Load to texture
  78335. var x_start, y_start, x_step, y_step, y_end, x_end;
  78336. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  78337. default:
  78338. case TGATools._ORIGIN_UL:
  78339. x_start = 0;
  78340. x_step = 1;
  78341. x_end = header.width;
  78342. y_start = 0;
  78343. y_step = 1;
  78344. y_end = header.height;
  78345. break;
  78346. case TGATools._ORIGIN_BL:
  78347. x_start = 0;
  78348. x_step = 1;
  78349. x_end = header.width;
  78350. y_start = header.height - 1;
  78351. y_step = -1;
  78352. y_end = -1;
  78353. break;
  78354. case TGATools._ORIGIN_UR:
  78355. x_start = header.width - 1;
  78356. x_step = -1;
  78357. x_end = -1;
  78358. y_start = 0;
  78359. y_step = 1;
  78360. y_end = header.height;
  78361. break;
  78362. case TGATools._ORIGIN_BR:
  78363. x_start = header.width - 1;
  78364. x_step = -1;
  78365. x_end = -1;
  78366. y_start = header.height - 1;
  78367. y_step = -1;
  78368. y_end = -1;
  78369. break;
  78370. }
  78371. // Load the specify method
  78372. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  78373. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  78374. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  78375. };
  78376. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78377. var image = pixel_data, colormap = palettes;
  78378. var width = header.width, height = header.height;
  78379. var color, i = 0, x, y;
  78380. var imageData = new Uint8Array(width * height * 4);
  78381. for (y = y_start; y !== y_end; y += y_step) {
  78382. for (x = x_start; x !== x_end; x += x_step, i++) {
  78383. color = image[i];
  78384. imageData[(x + width * y) * 4 + 3] = 255;
  78385. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  78386. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  78387. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  78388. }
  78389. }
  78390. return imageData;
  78391. };
  78392. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78393. var image = pixel_data;
  78394. var width = header.width, height = header.height;
  78395. var color, i = 0, x, y;
  78396. var imageData = new Uint8Array(width * height * 4);
  78397. for (y = y_start; y !== y_end; y += y_step) {
  78398. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78399. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  78400. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  78401. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  78402. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  78403. imageData[(x + width * y) * 4 + 0] = r;
  78404. imageData[(x + width * y) * 4 + 1] = g;
  78405. imageData[(x + width * y) * 4 + 2] = b;
  78406. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  78407. }
  78408. }
  78409. return imageData;
  78410. };
  78411. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78412. var image = pixel_data;
  78413. var width = header.width, height = header.height;
  78414. var i = 0, x, y;
  78415. var imageData = new Uint8Array(width * height * 4);
  78416. for (y = y_start; y !== y_end; y += y_step) {
  78417. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  78418. imageData[(x + width * y) * 4 + 3] = 255;
  78419. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78420. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78421. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78422. }
  78423. }
  78424. return imageData;
  78425. };
  78426. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78427. var image = pixel_data;
  78428. var width = header.width, height = header.height;
  78429. var i = 0, x, y;
  78430. var imageData = new Uint8Array(width * height * 4);
  78431. for (y = y_start; y !== y_end; y += y_step) {
  78432. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  78433. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78434. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78435. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78436. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  78437. }
  78438. }
  78439. return imageData;
  78440. };
  78441. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78442. var image = pixel_data;
  78443. var width = header.width, height = header.height;
  78444. var color, i = 0, x, y;
  78445. var imageData = new Uint8Array(width * height * 4);
  78446. for (y = y_start; y !== y_end; y += y_step) {
  78447. for (x = x_start; x !== x_end; x += x_step, i++) {
  78448. color = image[i];
  78449. imageData[(x + width * y) * 4 + 0] = color;
  78450. imageData[(x + width * y) * 4 + 1] = color;
  78451. imageData[(x + width * y) * 4 + 2] = color;
  78452. imageData[(x + width * y) * 4 + 3] = 255;
  78453. }
  78454. }
  78455. return imageData;
  78456. };
  78457. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78458. var image = pixel_data;
  78459. var width = header.width, height = header.height;
  78460. var i = 0, x, y;
  78461. var imageData = new Uint8Array(width * height * 4);
  78462. for (y = y_start; y !== y_end; y += y_step) {
  78463. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78464. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  78465. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  78466. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78467. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  78468. }
  78469. }
  78470. return imageData;
  78471. };
  78472. //private static _TYPE_NO_DATA = 0;
  78473. TGATools._TYPE_INDEXED = 1;
  78474. TGATools._TYPE_RGB = 2;
  78475. TGATools._TYPE_GREY = 3;
  78476. TGATools._TYPE_RLE_INDEXED = 9;
  78477. TGATools._TYPE_RLE_RGB = 10;
  78478. TGATools._TYPE_RLE_GREY = 11;
  78479. TGATools._ORIGIN_MASK = 0x30;
  78480. TGATools._ORIGIN_SHIFT = 0x04;
  78481. TGATools._ORIGIN_BL = 0x00;
  78482. TGATools._ORIGIN_BR = 0x01;
  78483. TGATools._ORIGIN_UL = 0x02;
  78484. TGATools._ORIGIN_UR = 0x03;
  78485. return TGATools;
  78486. }());
  78487. BABYLON.TGATools = TGATools;
  78488. })(BABYLON || (BABYLON = {}));
  78489. //# sourceMappingURL=babylon.tga.js.map
  78490. var BABYLON;
  78491. (function (BABYLON) {
  78492. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  78493. // All values and structures referenced from:
  78494. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  78495. var DDS_MAGIC = 0x20534444;
  78496. var
  78497. //DDSD_CAPS = 0x1,
  78498. //DDSD_HEIGHT = 0x2,
  78499. //DDSD_WIDTH = 0x4,
  78500. //DDSD_PITCH = 0x8,
  78501. //DDSD_PIXELFORMAT = 0x1000,
  78502. DDSD_MIPMAPCOUNT = 0x20000;
  78503. //DDSD_LINEARSIZE = 0x80000,
  78504. //DDSD_DEPTH = 0x800000;
  78505. // var DDSCAPS_COMPLEX = 0x8,
  78506. // DDSCAPS_MIPMAP = 0x400000,
  78507. // DDSCAPS_TEXTURE = 0x1000;
  78508. var DDSCAPS2_CUBEMAP = 0x200;
  78509. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  78510. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  78511. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  78512. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  78513. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  78514. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  78515. // DDSCAPS2_VOLUME = 0x200000;
  78516. var
  78517. //DDPF_ALPHAPIXELS = 0x1,
  78518. //DDPF_ALPHA = 0x2,
  78519. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  78520. //DDPF_YUV = 0x200,
  78521. DDPF_LUMINANCE = 0x20000;
  78522. function FourCCToInt32(value) {
  78523. return value.charCodeAt(0) +
  78524. (value.charCodeAt(1) << 8) +
  78525. (value.charCodeAt(2) << 16) +
  78526. (value.charCodeAt(3) << 24);
  78527. }
  78528. function Int32ToFourCC(value) {
  78529. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  78530. }
  78531. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  78532. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  78533. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  78534. var FOURCC_DX10 = FourCCToInt32("DX10");
  78535. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  78536. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  78537. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  78538. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  78539. var headerLengthInt = 31; // The header length in 32 bit ints
  78540. // Offsets into the header array
  78541. var off_magic = 0;
  78542. var off_size = 1;
  78543. var off_flags = 2;
  78544. var off_height = 3;
  78545. var off_width = 4;
  78546. var off_mipmapCount = 7;
  78547. var off_pfFlags = 20;
  78548. var off_pfFourCC = 21;
  78549. var off_RGBbpp = 22;
  78550. var off_RMask = 23;
  78551. var off_GMask = 24;
  78552. var off_BMask = 25;
  78553. var off_AMask = 26;
  78554. // var off_caps1 = 27;
  78555. var off_caps2 = 28;
  78556. // var off_caps3 = 29;
  78557. // var off_caps4 = 30;
  78558. var off_dxgiFormat = 32;
  78559. ;
  78560. var DDSTools = /** @class */ (function () {
  78561. function DDSTools() {
  78562. }
  78563. DDSTools.GetDDSInfo = function (arrayBuffer) {
  78564. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78565. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  78566. var mipmapCount = 1;
  78567. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  78568. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78569. }
  78570. var fourCC = header[off_pfFourCC];
  78571. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  78572. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78573. switch (fourCC) {
  78574. case FOURCC_D3DFMT_R16G16B16A16F:
  78575. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78576. break;
  78577. case FOURCC_D3DFMT_R32G32B32A32F:
  78578. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78579. break;
  78580. case FOURCC_DX10:
  78581. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  78582. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78583. break;
  78584. }
  78585. }
  78586. return {
  78587. width: header[off_width],
  78588. height: header[off_height],
  78589. mipmapCount: mipmapCount,
  78590. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  78591. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  78592. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  78593. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  78594. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  78595. dxgiFormat: dxgiFormat,
  78596. textureType: textureType
  78597. };
  78598. };
  78599. DDSTools._ToHalfFloat = function (value) {
  78600. if (!DDSTools._FloatView) {
  78601. DDSTools._FloatView = new Float32Array(1);
  78602. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  78603. }
  78604. DDSTools._FloatView[0] = value;
  78605. var x = DDSTools._Int32View[0];
  78606. var bits = (x >> 16) & 0x8000; /* Get the sign */
  78607. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  78608. var e = (x >> 23) & 0xff; /* Using int is faster here */
  78609. /* If zero, or denormal, or exponent underflows too much for a denormal
  78610. * half, return signed zero. */
  78611. if (e < 103) {
  78612. return bits;
  78613. }
  78614. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  78615. if (e > 142) {
  78616. bits |= 0x7c00;
  78617. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  78618. * not Inf, so make sure we set one mantissa bit too. */
  78619. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  78620. return bits;
  78621. }
  78622. /* If exponent underflows but not too much, return a denormal */
  78623. if (e < 113) {
  78624. m |= 0x0800;
  78625. /* Extra rounding may overflow and set mantissa to 0 and exponent
  78626. * to 1, which is OK. */
  78627. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  78628. return bits;
  78629. }
  78630. bits |= ((e - 112) << 10) | (m >> 1);
  78631. bits += m & 1;
  78632. return bits;
  78633. };
  78634. DDSTools._FromHalfFloat = function (value) {
  78635. var s = (value & 0x8000) >> 15;
  78636. var e = (value & 0x7C00) >> 10;
  78637. var f = value & 0x03FF;
  78638. if (e === 0) {
  78639. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  78640. }
  78641. else if (e == 0x1F) {
  78642. return f ? NaN : ((s ? -1 : 1) * Infinity);
  78643. }
  78644. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  78645. };
  78646. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78647. var destArray = new Float32Array(dataLength);
  78648. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78649. var index = 0;
  78650. for (var y = 0; y < height; y++) {
  78651. for (var x = 0; x < width; x++) {
  78652. var srcPos = (x + y * width) * 4;
  78653. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  78654. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  78655. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  78656. if (DDSTools.StoreLODInAlphaChannel) {
  78657. destArray[index + 3] = lod;
  78658. }
  78659. else {
  78660. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  78661. }
  78662. index += 4;
  78663. }
  78664. }
  78665. return destArray;
  78666. };
  78667. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78668. if (DDSTools.StoreLODInAlphaChannel) {
  78669. var destArray = new Uint16Array(dataLength);
  78670. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78671. var index = 0;
  78672. for (var y = 0; y < height; y++) {
  78673. for (var x = 0; x < width; x++) {
  78674. var srcPos = (x + y * width) * 4;
  78675. destArray[index] = srcData[srcPos];
  78676. destArray[index + 1] = srcData[srcPos + 1];
  78677. destArray[index + 2] = srcData[srcPos + 2];
  78678. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  78679. index += 4;
  78680. }
  78681. }
  78682. return destArray;
  78683. }
  78684. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  78685. };
  78686. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78687. if (DDSTools.StoreLODInAlphaChannel) {
  78688. var destArray = new Float32Array(dataLength);
  78689. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78690. var index = 0;
  78691. for (var y = 0; y < height; y++) {
  78692. for (var x = 0; x < width; x++) {
  78693. var srcPos = (x + y * width) * 4;
  78694. destArray[index] = srcData[srcPos];
  78695. destArray[index + 1] = srcData[srcPos + 1];
  78696. destArray[index + 2] = srcData[srcPos + 2];
  78697. destArray[index + 3] = lod;
  78698. index += 4;
  78699. }
  78700. }
  78701. return destArray;
  78702. }
  78703. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  78704. };
  78705. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78706. var destArray = new Uint8Array(dataLength);
  78707. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78708. var index = 0;
  78709. for (var y = 0; y < height; y++) {
  78710. for (var x = 0; x < width; x++) {
  78711. var srcPos = (x + y * width) * 4;
  78712. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  78713. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  78714. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  78715. if (DDSTools.StoreLODInAlphaChannel) {
  78716. destArray[index + 3] = lod;
  78717. }
  78718. else {
  78719. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  78720. }
  78721. index += 4;
  78722. }
  78723. }
  78724. return destArray;
  78725. };
  78726. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78727. var destArray = new Uint8Array(dataLength);
  78728. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78729. var index = 0;
  78730. for (var y = 0; y < height; y++) {
  78731. for (var x = 0; x < width; x++) {
  78732. var srcPos = (x + y * width) * 4;
  78733. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  78734. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  78735. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  78736. if (DDSTools.StoreLODInAlphaChannel) {
  78737. destArray[index + 3] = lod;
  78738. }
  78739. else {
  78740. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  78741. }
  78742. index += 4;
  78743. }
  78744. }
  78745. return destArray;
  78746. };
  78747. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  78748. var byteArray = new Uint8Array(dataLength);
  78749. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78750. var index = 0;
  78751. for (var y = 0; y < height; y++) {
  78752. for (var x = 0; x < width; x++) {
  78753. var srcPos = (x + y * width) * 4;
  78754. byteArray[index] = srcData[srcPos + rOffset];
  78755. byteArray[index + 1] = srcData[srcPos + gOffset];
  78756. byteArray[index + 2] = srcData[srcPos + bOffset];
  78757. byteArray[index + 3] = srcData[srcPos + aOffset];
  78758. index += 4;
  78759. }
  78760. }
  78761. return byteArray;
  78762. };
  78763. DDSTools._ExtractLongWordOrder = function (value) {
  78764. if (value === 0 || value === 255 || value === -16777216) {
  78765. return 0;
  78766. }
  78767. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  78768. };
  78769. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  78770. var byteArray = new Uint8Array(dataLength);
  78771. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78772. var index = 0;
  78773. for (var y = 0; y < height; y++) {
  78774. for (var x = 0; x < width; x++) {
  78775. var srcPos = (x + y * width) * 3;
  78776. byteArray[index] = srcData[srcPos + rOffset];
  78777. byteArray[index + 1] = srcData[srcPos + gOffset];
  78778. byteArray[index + 2] = srcData[srcPos + bOffset];
  78779. index += 3;
  78780. }
  78781. }
  78782. return byteArray;
  78783. };
  78784. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  78785. var byteArray = new Uint8Array(dataLength);
  78786. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78787. var index = 0;
  78788. for (var y = 0; y < height; y++) {
  78789. for (var x = 0; x < width; x++) {
  78790. var srcPos = (x + y * width);
  78791. byteArray[index] = srcData[srcPos];
  78792. index++;
  78793. }
  78794. }
  78795. return byteArray;
  78796. };
  78797. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  78798. if (lodIndex === void 0) { lodIndex = -1; }
  78799. var ext = engine.getCaps().s3tc;
  78800. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78801. var fourCC, width, height, dataLength = 0, dataOffset;
  78802. var byteArray, mipmapCount, mip;
  78803. var internalFormat = 0;
  78804. var format = 0;
  78805. var blockBytes = 1;
  78806. if (header[off_magic] !== DDS_MAGIC) {
  78807. BABYLON.Tools.Error("Invalid magic number in DDS header");
  78808. return;
  78809. }
  78810. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  78811. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  78812. return;
  78813. }
  78814. if (info.isCompressed && !ext) {
  78815. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  78816. return;
  78817. }
  78818. var bpp = header[off_RGBbpp];
  78819. dataOffset = header[off_size] + 4;
  78820. var computeFormats = false;
  78821. if (info.isFourCC) {
  78822. fourCC = header[off_pfFourCC];
  78823. switch (fourCC) {
  78824. case FOURCC_DXT1:
  78825. blockBytes = 8;
  78826. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  78827. break;
  78828. case FOURCC_DXT3:
  78829. blockBytes = 16;
  78830. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  78831. break;
  78832. case FOURCC_DXT5:
  78833. blockBytes = 16;
  78834. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  78835. break;
  78836. case FOURCC_D3DFMT_R16G16B16A16F:
  78837. computeFormats = true;
  78838. break;
  78839. case FOURCC_D3DFMT_R32G32B32A32F:
  78840. computeFormats = true;
  78841. break;
  78842. case FOURCC_DX10:
  78843. // There is an additionnal header so dataOffset need to be changed
  78844. dataOffset += 5 * 4; // 5 uints
  78845. var supported = false;
  78846. switch (info.dxgiFormat) {
  78847. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  78848. computeFormats = true;
  78849. supported = true;
  78850. break;
  78851. case DXGI_FORMAT_B8G8R8X8_UNORM:
  78852. info.isRGB = true;
  78853. info.isFourCC = false;
  78854. bpp = 32;
  78855. supported = true;
  78856. break;
  78857. }
  78858. if (supported) {
  78859. break;
  78860. }
  78861. default:
  78862. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  78863. return;
  78864. }
  78865. }
  78866. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  78867. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  78868. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  78869. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  78870. if (computeFormats) {
  78871. format = engine._getWebGLTextureType(info.textureType);
  78872. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78873. }
  78874. mipmapCount = 1;
  78875. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  78876. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78877. }
  78878. for (var face = 0; face < faces; face++) {
  78879. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  78880. width = header[off_width];
  78881. height = header[off_height];
  78882. for (mip = 0; mip < mipmapCount; ++mip) {
  78883. if (lodIndex === -1 || lodIndex === mip) {
  78884. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  78885. var i = (lodIndex === -1) ? mip : 0;
  78886. if (!info.isCompressed && info.isFourCC) {
  78887. dataLength = width * height * 4;
  78888. var floatArray = null;
  78889. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  78890. if (bpp === 128) {
  78891. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78892. }
  78893. else if (bpp === 64) {
  78894. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78895. }
  78896. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78897. format = engine._getWebGLTextureType(info.textureType);
  78898. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78899. }
  78900. else {
  78901. if (bpp === 128) {
  78902. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78903. }
  78904. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  78905. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78906. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78907. format = engine._getWebGLTextureType(info.textureType);
  78908. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78909. }
  78910. else {
  78911. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78912. }
  78913. }
  78914. if (floatArray) {
  78915. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  78916. }
  78917. }
  78918. else if (info.isRGB) {
  78919. if (bpp === 24) {
  78920. dataLength = width * height * 3;
  78921. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  78922. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  78923. }
  78924. else {
  78925. dataLength = width * height * 4;
  78926. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  78927. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  78928. }
  78929. }
  78930. else if (info.isLuminance) {
  78931. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  78932. var unpaddedRowSize = width;
  78933. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  78934. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  78935. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  78936. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  78937. }
  78938. else {
  78939. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  78940. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  78941. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  78942. }
  78943. }
  78944. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  78945. width *= 0.5;
  78946. height *= 0.5;
  78947. width = Math.max(1.0, width);
  78948. height = Math.max(1.0, height);
  78949. }
  78950. if (currentFace !== undefined) {
  78951. // Loading a single face
  78952. break;
  78953. }
  78954. }
  78955. };
  78956. DDSTools.StoreLODInAlphaChannel = false;
  78957. return DDSTools;
  78958. }());
  78959. BABYLON.DDSTools = DDSTools;
  78960. })(BABYLON || (BABYLON = {}));
  78961. //# sourceMappingURL=babylon.dds.js.map
  78962. var BABYLON;
  78963. (function (BABYLON) {
  78964. /**
  78965. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  78966. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  78967. */
  78968. var KhronosTextureContainer = /** @class */ (function () {
  78969. /**
  78970. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  78971. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  78972. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  78973. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  78974. */
  78975. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  78976. this.arrayBuffer = arrayBuffer;
  78977. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  78978. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  78979. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  78980. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  78981. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  78982. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  78983. BABYLON.Tools.Error("texture missing KTX identifier");
  78984. return;
  78985. }
  78986. // load the reset of the header in native 32 bit int
  78987. var header = new Int32Array(this.arrayBuffer, 12, 13);
  78988. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  78989. var oppositeEndianess = header[0] === 0x01020304;
  78990. // read all the header elements in order they exist in the file, without modification (sans endainness)
  78991. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  78992. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  78993. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  78994. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  78995. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  78996. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  78997. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  78998. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  78999. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  79000. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  79001. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  79002. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  79003. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  79004. if (this.glType !== 0) {
  79005. BABYLON.Tools.Error("only compressed formats currently supported");
  79006. return;
  79007. }
  79008. else {
  79009. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  79010. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  79011. }
  79012. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  79013. BABYLON.Tools.Error("only 2D textures currently supported");
  79014. return;
  79015. }
  79016. if (this.numberOfArrayElements !== 0) {
  79017. BABYLON.Tools.Error("texture arrays not currently supported");
  79018. return;
  79019. }
  79020. if (this.numberOfFaces !== facesExpected) {
  79021. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  79022. return;
  79023. }
  79024. // we now have a completely validated file, so could use existence of loadType as success
  79025. // would need to make this more elaborate & adjust checks above to support more than one load type
  79026. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  79027. }
  79028. // not as fast hardware based, but will probably never need to use
  79029. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  79030. return ((val & 0xFF) << 24)
  79031. | ((val & 0xFF00) << 8)
  79032. | ((val >> 8) & 0xFF00)
  79033. | ((val >> 24) & 0xFF);
  79034. };
  79035. /**
  79036. * It is assumed that the texture has already been created & is currently bound
  79037. */
  79038. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  79039. switch (this.loadType) {
  79040. case KhronosTextureContainer.COMPRESSED_2D:
  79041. this._upload2DCompressedLevels(gl, loadMipmaps);
  79042. break;
  79043. case KhronosTextureContainer.TEX_2D:
  79044. case KhronosTextureContainer.COMPRESSED_3D:
  79045. case KhronosTextureContainer.TEX_3D:
  79046. }
  79047. };
  79048. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  79049. // initialize width & height for level 1
  79050. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  79051. var width = this.pixelWidth;
  79052. var height = this.pixelHeight;
  79053. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  79054. for (var level = 0; level < mipmapCount; level++) {
  79055. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  79056. for (var face = 0; face < this.numberOfFaces; face++) {
  79057. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  79058. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  79059. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  79060. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  79061. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  79062. }
  79063. width = Math.max(1.0, width * 0.5);
  79064. height = Math.max(1.0, height * 0.5);
  79065. }
  79066. };
  79067. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  79068. // load types
  79069. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  79070. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  79071. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  79072. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  79073. return KhronosTextureContainer;
  79074. }());
  79075. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  79076. })(BABYLON || (BABYLON = {}));
  79077. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  79078. var BABYLON;
  79079. (function (BABYLON) {
  79080. var Debug = /** @class */ (function () {
  79081. function Debug() {
  79082. }
  79083. Debug.AxesViewer = /** @class */ (function () {
  79084. function AxesViewer(scene, scaleLines) {
  79085. if (scaleLines === void 0) { scaleLines = 1; }
  79086. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79087. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79088. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79089. this.scaleLines = 1;
  79090. this.scaleLines = scaleLines;
  79091. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  79092. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  79093. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  79094. this._xmesh.renderingGroupId = 2;
  79095. this._ymesh.renderingGroupId = 2;
  79096. this._zmesh.renderingGroupId = 2;
  79097. this._xmesh.material.checkReadyOnlyOnce = true;
  79098. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  79099. this._ymesh.material.checkReadyOnlyOnce = true;
  79100. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  79101. this._zmesh.material.checkReadyOnlyOnce = true;
  79102. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  79103. this.scene = scene;
  79104. }
  79105. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  79106. var scaleLines = this.scaleLines;
  79107. if (this._xmesh) {
  79108. this._xmesh.position.copyFrom(position);
  79109. }
  79110. if (this._ymesh) {
  79111. this._ymesh.position.copyFrom(position);
  79112. }
  79113. if (this._zmesh) {
  79114. this._zmesh.position.copyFrom(position);
  79115. }
  79116. var point2 = this._xline[1];
  79117. point2.x = xaxis.x * scaleLines;
  79118. point2.y = xaxis.y * scaleLines;
  79119. point2.z = xaxis.z * scaleLines;
  79120. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  79121. point2 = this._yline[1];
  79122. point2.x = yaxis.x * scaleLines;
  79123. point2.y = yaxis.y * scaleLines;
  79124. point2.z = yaxis.z * scaleLines;
  79125. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  79126. point2 = this._zline[1];
  79127. point2.x = zaxis.x * scaleLines;
  79128. point2.y = zaxis.y * scaleLines;
  79129. point2.z = zaxis.z * scaleLines;
  79130. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  79131. };
  79132. AxesViewer.prototype.dispose = function () {
  79133. if (this._xmesh) {
  79134. this._xmesh.dispose();
  79135. }
  79136. if (this._ymesh) {
  79137. this._ymesh.dispose();
  79138. }
  79139. if (this._zmesh) {
  79140. this._zmesh.dispose();
  79141. }
  79142. this._xmesh = null;
  79143. this._ymesh = null;
  79144. this._zmesh = null;
  79145. this.scene = null;
  79146. };
  79147. return AxesViewer;
  79148. }());
  79149. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  79150. __extends(BoneAxesViewer, _super);
  79151. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  79152. if (scaleLines === void 0) { scaleLines = 1; }
  79153. var _this = _super.call(this, scene, scaleLines) || this;
  79154. _this.pos = BABYLON.Vector3.Zero();
  79155. _this.xaxis = BABYLON.Vector3.Zero();
  79156. _this.yaxis = BABYLON.Vector3.Zero();
  79157. _this.zaxis = BABYLON.Vector3.Zero();
  79158. _this.mesh = mesh;
  79159. _this.bone = bone;
  79160. return _this;
  79161. }
  79162. BoneAxesViewer.prototype.update = function () {
  79163. if (!this.mesh || !this.bone) {
  79164. return;
  79165. }
  79166. var bone = this.bone;
  79167. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  79168. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  79169. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  79170. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  79171. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  79172. };
  79173. BoneAxesViewer.prototype.dispose = function () {
  79174. if (this.mesh) {
  79175. this.mesh = null;
  79176. this.bone = null;
  79177. _super.prototype.dispose.call(this);
  79178. }
  79179. };
  79180. return BoneAxesViewer;
  79181. }(Debug.AxesViewer));
  79182. Debug.PhysicsViewer = /** @class */ (function () {
  79183. function PhysicsViewer(scene) {
  79184. this._impostors = [];
  79185. this._meshes = [];
  79186. this._numMeshes = 0;
  79187. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79188. var physicEngine = this._scene.getPhysicsEngine();
  79189. if (physicEngine) {
  79190. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  79191. }
  79192. }
  79193. PhysicsViewer.prototype._updateDebugMeshes = function () {
  79194. var plugin = this._physicsEnginePlugin;
  79195. for (var i = 0; i < this._numMeshes; i++) {
  79196. var impostor = this._impostors[i];
  79197. if (!impostor) {
  79198. continue;
  79199. }
  79200. if (impostor.isDisposed) {
  79201. this.hideImpostor(this._impostors[i--]);
  79202. }
  79203. else {
  79204. var mesh = this._meshes[i];
  79205. if (mesh && plugin) {
  79206. plugin.syncMeshWithImpostor(mesh, impostor);
  79207. }
  79208. }
  79209. }
  79210. };
  79211. PhysicsViewer.prototype.showImpostor = function (impostor) {
  79212. if (!this._scene) {
  79213. return;
  79214. }
  79215. for (var i = 0; i < this._numMeshes; i++) {
  79216. if (this._impostors[i] == impostor) {
  79217. return;
  79218. }
  79219. }
  79220. var debugMesh = this._getDebugMesh(impostor, this._scene);
  79221. if (debugMesh) {
  79222. this._impostors[this._numMeshes] = impostor;
  79223. this._meshes[this._numMeshes] = debugMesh;
  79224. if (this._numMeshes === 0) {
  79225. this._renderFunction = this._updateDebugMeshes.bind(this);
  79226. this._scene.registerBeforeRender(this._renderFunction);
  79227. }
  79228. this._numMeshes++;
  79229. }
  79230. };
  79231. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  79232. if (!impostor || !this._scene) {
  79233. return;
  79234. }
  79235. var removed = false;
  79236. for (var i = 0; i < this._numMeshes; i++) {
  79237. if (this._impostors[i] == impostor) {
  79238. var mesh = this._meshes[i];
  79239. if (!mesh) {
  79240. continue;
  79241. }
  79242. this._scene.removeMesh(mesh);
  79243. mesh.dispose();
  79244. this._numMeshes--;
  79245. if (this._numMeshes > 0) {
  79246. this._meshes[i] = this._meshes[this._numMeshes];
  79247. this._impostors[i] = this._impostors[this._numMeshes];
  79248. this._meshes[this._numMeshes] = null;
  79249. this._impostors[this._numMeshes] = null;
  79250. }
  79251. else {
  79252. this._meshes[0] = null;
  79253. this._impostors[0] = null;
  79254. }
  79255. removed = true;
  79256. break;
  79257. }
  79258. }
  79259. if (removed && this._numMeshes === 0) {
  79260. this._scene.unregisterBeforeRender(this._renderFunction);
  79261. }
  79262. };
  79263. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  79264. if (!this._debugMaterial) {
  79265. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  79266. this._debugMaterial.wireframe = true;
  79267. }
  79268. return this._debugMaterial;
  79269. };
  79270. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  79271. if (!this._debugBoxMesh) {
  79272. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  79273. this._debugBoxMesh.renderingGroupId = 1;
  79274. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79275. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  79276. scene.removeMesh(this._debugBoxMesh);
  79277. }
  79278. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  79279. };
  79280. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  79281. if (!this._debugSphereMesh) {
  79282. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  79283. this._debugSphereMesh.renderingGroupId = 1;
  79284. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79285. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  79286. scene.removeMesh(this._debugSphereMesh);
  79287. }
  79288. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  79289. };
  79290. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  79291. var mesh = null;
  79292. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  79293. mesh = this._getDebugBoxMesh(scene);
  79294. impostor.getBoxSizeToRef(mesh.scaling);
  79295. }
  79296. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  79297. mesh = this._getDebugSphereMesh(scene);
  79298. var radius = impostor.getRadius();
  79299. mesh.scaling.x = radius * 2;
  79300. mesh.scaling.y = radius * 2;
  79301. mesh.scaling.z = radius * 2;
  79302. }
  79303. return mesh;
  79304. };
  79305. PhysicsViewer.prototype.dispose = function () {
  79306. for (var i = 0; i < this._numMeshes; i++) {
  79307. this.hideImpostor(this._impostors[i]);
  79308. }
  79309. if (this._debugBoxMesh) {
  79310. this._debugBoxMesh.dispose();
  79311. }
  79312. if (this._debugSphereMesh) {
  79313. this._debugSphereMesh.dispose();
  79314. }
  79315. if (this._debugMaterial) {
  79316. this._debugMaterial.dispose();
  79317. }
  79318. this._impostors.length = 0;
  79319. this._scene = null;
  79320. this._physicsEnginePlugin = null;
  79321. };
  79322. return PhysicsViewer;
  79323. }());
  79324. Debug.SkeletonViewer = /** @class */ (function () {
  79325. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  79326. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  79327. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  79328. this.skeleton = skeleton;
  79329. this.mesh = mesh;
  79330. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  79331. this.renderingGroupId = renderingGroupId;
  79332. this.color = BABYLON.Color3.White();
  79333. this._debugLines = new Array();
  79334. this._isEnabled = false;
  79335. this._scene = scene;
  79336. this.update();
  79337. this._renderFunction = this.update.bind(this);
  79338. }
  79339. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  79340. get: function () {
  79341. return this._isEnabled;
  79342. },
  79343. set: function (value) {
  79344. if (this._isEnabled === value) {
  79345. return;
  79346. }
  79347. this._isEnabled = value;
  79348. if (value) {
  79349. this._scene.registerBeforeRender(this._renderFunction);
  79350. }
  79351. else {
  79352. this._scene.unregisterBeforeRender(this._renderFunction);
  79353. }
  79354. },
  79355. enumerable: true,
  79356. configurable: true
  79357. });
  79358. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  79359. if (x === void 0) { x = 0; }
  79360. if (y === void 0) { y = 0; }
  79361. if (z === void 0) { z = 0; }
  79362. var tmat = BABYLON.Tmp.Matrix[0];
  79363. var parentBone = bone.getParent();
  79364. tmat.copyFrom(bone.getLocalMatrix());
  79365. if (x !== 0 || y !== 0 || z !== 0) {
  79366. var tmat2 = BABYLON.Tmp.Matrix[1];
  79367. BABYLON.Matrix.IdentityToRef(tmat2);
  79368. tmat2.m[12] = x;
  79369. tmat2.m[13] = y;
  79370. tmat2.m[14] = z;
  79371. tmat2.multiplyToRef(tmat, tmat);
  79372. }
  79373. if (parentBone) {
  79374. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  79375. }
  79376. tmat.multiplyToRef(meshMat, tmat);
  79377. position.x = tmat.m[12];
  79378. position.y = tmat.m[13];
  79379. position.z = tmat.m[14];
  79380. };
  79381. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  79382. var len = bones.length;
  79383. var meshPos = this.mesh.position;
  79384. for (var i = 0; i < len; i++) {
  79385. var bone = bones[i];
  79386. var points = this._debugLines[i];
  79387. if (!points) {
  79388. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79389. this._debugLines[i] = points;
  79390. }
  79391. this._getBonePosition(points[0], bone, meshMat);
  79392. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  79393. points[0].subtractInPlace(meshPos);
  79394. points[1].subtractInPlace(meshPos);
  79395. }
  79396. };
  79397. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  79398. var len = bones.length;
  79399. var boneNum = 0;
  79400. var meshPos = this.mesh.position;
  79401. for (var i = len - 1; i >= 0; i--) {
  79402. var childBone = bones[i];
  79403. var parentBone = childBone.getParent();
  79404. if (!parentBone) {
  79405. continue;
  79406. }
  79407. var points = this._debugLines[boneNum];
  79408. if (!points) {
  79409. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79410. this._debugLines[boneNum] = points;
  79411. }
  79412. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  79413. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  79414. points[0].subtractInPlace(meshPos);
  79415. points[1].subtractInPlace(meshPos);
  79416. boneNum++;
  79417. }
  79418. };
  79419. SkeletonViewer.prototype.update = function () {
  79420. if (this.autoUpdateBonesMatrices) {
  79421. this.skeleton.computeAbsoluteTransforms();
  79422. }
  79423. if (this.skeleton.bones[0].length === undefined) {
  79424. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79425. }
  79426. else {
  79427. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79428. }
  79429. if (!this._debugMesh) {
  79430. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  79431. this._debugMesh.renderingGroupId = this.renderingGroupId;
  79432. }
  79433. else {
  79434. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  79435. }
  79436. this._debugMesh.position.copyFrom(this.mesh.position);
  79437. this._debugMesh.color = this.color;
  79438. };
  79439. SkeletonViewer.prototype.dispose = function () {
  79440. if (this._debugMesh) {
  79441. this.isEnabled = false;
  79442. this._debugMesh.dispose();
  79443. this._debugMesh = null;
  79444. }
  79445. };
  79446. return SkeletonViewer;
  79447. }());
  79448. return Debug;
  79449. }());
  79450. BABYLON.Debug = Debug;
  79451. })(BABYLON || (BABYLON = {}));
  79452. //# sourceMappingURL=babylon.debugModules.js.map
  79453. var BABYLON;
  79454. (function (BABYLON) {
  79455. var RayHelper = /** @class */ (function () {
  79456. function RayHelper(ray) {
  79457. this.ray = ray;
  79458. }
  79459. RayHelper.CreateAndShow = function (ray, scene, color) {
  79460. var helper = new RayHelper(ray);
  79461. helper.show(scene, color);
  79462. return helper;
  79463. };
  79464. RayHelper.prototype.show = function (scene, color) {
  79465. if (!this._renderFunction && this.ray) {
  79466. var ray = this.ray;
  79467. this._renderFunction = this._render.bind(this);
  79468. this._scene = scene;
  79469. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  79470. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  79471. if (this._renderFunction) {
  79472. this._scene.registerBeforeRender(this._renderFunction);
  79473. }
  79474. }
  79475. if (color && this._renderLine) {
  79476. this._renderLine.color.copyFrom(color);
  79477. }
  79478. };
  79479. RayHelper.prototype.hide = function () {
  79480. if (this._renderFunction && this._scene) {
  79481. this._scene.unregisterBeforeRender(this._renderFunction);
  79482. this._scene = null;
  79483. this._renderFunction = null;
  79484. if (this._renderLine) {
  79485. this._renderLine.dispose();
  79486. this._renderLine = null;
  79487. }
  79488. this._renderPoints = [];
  79489. }
  79490. };
  79491. RayHelper.prototype._render = function () {
  79492. var ray = this.ray;
  79493. if (!ray) {
  79494. return;
  79495. }
  79496. var point = this._renderPoints[1];
  79497. var len = Math.min(ray.length, 1000000);
  79498. point.copyFrom(ray.direction);
  79499. point.scaleInPlace(len);
  79500. point.addInPlace(ray.origin);
  79501. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  79502. };
  79503. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  79504. this._attachedToMesh = mesh;
  79505. var ray = this.ray;
  79506. if (!ray) {
  79507. return;
  79508. }
  79509. if (!ray.direction) {
  79510. ray.direction = BABYLON.Vector3.Zero();
  79511. }
  79512. if (!ray.origin) {
  79513. ray.origin = BABYLON.Vector3.Zero();
  79514. }
  79515. if (length) {
  79516. ray.length = length;
  79517. }
  79518. if (!meshSpaceOrigin) {
  79519. meshSpaceOrigin = BABYLON.Vector3.Zero();
  79520. }
  79521. if (!meshSpaceDirection) {
  79522. // -1 so that this will work with Mesh.lookAt
  79523. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  79524. }
  79525. if (!this._meshSpaceDirection) {
  79526. this._meshSpaceDirection = meshSpaceDirection.clone();
  79527. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  79528. }
  79529. else {
  79530. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  79531. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  79532. }
  79533. if (!this._updateToMeshFunction) {
  79534. this._updateToMeshFunction = this._updateToMesh.bind(this);
  79535. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  79536. }
  79537. this._updateToMesh();
  79538. };
  79539. RayHelper.prototype.detachFromMesh = function () {
  79540. if (this._attachedToMesh) {
  79541. if (this._updateToMeshFunction) {
  79542. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  79543. }
  79544. this._attachedToMesh = null;
  79545. this._updateToMeshFunction = null;
  79546. }
  79547. };
  79548. RayHelper.prototype._updateToMesh = function () {
  79549. var ray = this.ray;
  79550. if (!this._attachedToMesh || !ray) {
  79551. return;
  79552. }
  79553. if (this._attachedToMesh._isDisposed) {
  79554. this.detachFromMesh();
  79555. return;
  79556. }
  79557. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  79558. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  79559. };
  79560. RayHelper.prototype.dispose = function () {
  79561. this.hide();
  79562. this.detachFromMesh();
  79563. this.ray = null;
  79564. };
  79565. return RayHelper;
  79566. }());
  79567. BABYLON.RayHelper = RayHelper;
  79568. })(BABYLON || (BABYLON = {}));
  79569. //# sourceMappingURL=babylon.rayHelper.js.map
  79570. var BABYLON;
  79571. (function (BABYLON) {
  79572. // load the inspector using require, if not present in the global namespace.
  79573. var DebugLayer = /** @class */ (function () {
  79574. function DebugLayer(scene) {
  79575. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79576. this._scene = scene;
  79577. // load inspector using require, if it doesn't exist on the global namespace.
  79578. }
  79579. /** Creates the inspector window. */
  79580. DebugLayer.prototype._createInspector = function (config) {
  79581. if (config === void 0) { config = {}; }
  79582. var popup = config.popup || false;
  79583. var initialTab = config.initialTab || 0;
  79584. var parentElement = config.parentElement || null;
  79585. if (!this._inspector) {
  79586. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79587. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  79588. } // else nothing to do,; instance is already existing
  79589. };
  79590. DebugLayer.prototype.isVisible = function () {
  79591. if (!this._inspector) {
  79592. return false;
  79593. }
  79594. return true;
  79595. };
  79596. DebugLayer.prototype.hide = function () {
  79597. if (this._inspector) {
  79598. try {
  79599. this._inspector.dispose();
  79600. }
  79601. catch (e) {
  79602. // If the inspector has been removed directly from the inspector tool
  79603. }
  79604. this._inspector = null;
  79605. }
  79606. };
  79607. DebugLayer.prototype.show = function (config) {
  79608. if (config === void 0) { config = {}; }
  79609. if (typeof this.BJSINSPECTOR == 'undefined') {
  79610. // Load inspector and add it to the DOM
  79611. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  79612. }
  79613. else {
  79614. // Otherwise creates the inspector
  79615. this._createInspector(config);
  79616. }
  79617. };
  79618. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  79619. return DebugLayer;
  79620. }());
  79621. BABYLON.DebugLayer = DebugLayer;
  79622. })(BABYLON || (BABYLON = {}));
  79623. //# sourceMappingURL=babylon.debugLayer.js.map
  79624. var BABYLON;
  79625. (function (BABYLON) {
  79626. var BoundingBoxRenderer = /** @class */ (function () {
  79627. function BoundingBoxRenderer(scene) {
  79628. this.frontColor = new BABYLON.Color3(1, 1, 1);
  79629. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  79630. this.showBackLines = true;
  79631. this.renderList = new BABYLON.SmartArray(32);
  79632. this._vertexBuffers = {};
  79633. this._scene = scene;
  79634. }
  79635. BoundingBoxRenderer.prototype._prepareRessources = function () {
  79636. if (this._colorShader) {
  79637. return;
  79638. }
  79639. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  79640. attributes: [BABYLON.VertexBuffer.PositionKind],
  79641. uniforms: ["world", "viewProjection", "color"]
  79642. });
  79643. var engine = this._scene.getEngine();
  79644. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  79645. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  79646. this._createIndexBuffer();
  79647. };
  79648. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  79649. var engine = this._scene.getEngine();
  79650. 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]);
  79651. };
  79652. BoundingBoxRenderer.prototype._rebuild = function () {
  79653. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79654. if (vb) {
  79655. vb._rebuild();
  79656. }
  79657. this._createIndexBuffer();
  79658. };
  79659. BoundingBoxRenderer.prototype.reset = function () {
  79660. this.renderList.reset();
  79661. };
  79662. BoundingBoxRenderer.prototype.render = function () {
  79663. if (this.renderList.length === 0) {
  79664. return;
  79665. }
  79666. this._prepareRessources();
  79667. if (!this._colorShader.isReady()) {
  79668. return;
  79669. }
  79670. var engine = this._scene.getEngine();
  79671. engine.setDepthWrite(false);
  79672. this._colorShader._preBind();
  79673. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  79674. var boundingBox = this.renderList.data[boundingBoxIndex];
  79675. var min = boundingBox.minimum;
  79676. var max = boundingBox.maximum;
  79677. var diff = max.subtract(min);
  79678. var median = min.add(diff.scale(0.5));
  79679. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79680. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79681. .multiply(boundingBox.getWorldMatrix());
  79682. // VBOs
  79683. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79684. if (this.showBackLines) {
  79685. // Back
  79686. engine.setDepthFunctionToGreaterOrEqual();
  79687. this._scene.resetCachedMaterial();
  79688. this._colorShader.setColor4("color", this.backColor.toColor4());
  79689. this._colorShader.bind(worldMatrix);
  79690. // Draw order
  79691. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79692. }
  79693. // Front
  79694. engine.setDepthFunctionToLess();
  79695. this._scene.resetCachedMaterial();
  79696. this._colorShader.setColor4("color", this.frontColor.toColor4());
  79697. this._colorShader.bind(worldMatrix);
  79698. // Draw order
  79699. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79700. }
  79701. this._colorShader.unbind();
  79702. engine.setDepthFunctionToLessOrEqual();
  79703. engine.setDepthWrite(true);
  79704. };
  79705. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  79706. this._prepareRessources();
  79707. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  79708. return;
  79709. }
  79710. var engine = this._scene.getEngine();
  79711. engine.setDepthWrite(false);
  79712. engine.setColorWrite(false);
  79713. this._colorShader._preBind();
  79714. var boundingBox = mesh._boundingInfo.boundingBox;
  79715. var min = boundingBox.minimum;
  79716. var max = boundingBox.maximum;
  79717. var diff = max.subtract(min);
  79718. var median = min.add(diff.scale(0.5));
  79719. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79720. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79721. .multiply(boundingBox.getWorldMatrix());
  79722. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79723. engine.setDepthFunctionToLess();
  79724. this._scene.resetCachedMaterial();
  79725. this._colorShader.bind(worldMatrix);
  79726. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79727. this._colorShader.unbind();
  79728. engine.setDepthFunctionToLessOrEqual();
  79729. engine.setDepthWrite(true);
  79730. engine.setColorWrite(true);
  79731. };
  79732. BoundingBoxRenderer.prototype.dispose = function () {
  79733. if (!this._colorShader) {
  79734. return;
  79735. }
  79736. this.renderList.dispose();
  79737. this._colorShader.dispose();
  79738. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79739. if (buffer) {
  79740. buffer.dispose();
  79741. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79742. }
  79743. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79744. };
  79745. return BoundingBoxRenderer;
  79746. }());
  79747. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  79748. })(BABYLON || (BABYLON = {}));
  79749. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  79750. var BABYLON;
  79751. (function (BABYLON) {
  79752. var MorphTarget = /** @class */ (function () {
  79753. function MorphTarget(name, influence) {
  79754. if (influence === void 0) { influence = 0; }
  79755. this.name = name;
  79756. this.animations = new Array();
  79757. this._positions = null;
  79758. this._normals = null;
  79759. this._tangents = null;
  79760. this.onInfluenceChanged = new BABYLON.Observable();
  79761. this.influence = influence;
  79762. }
  79763. Object.defineProperty(MorphTarget.prototype, "influence", {
  79764. get: function () {
  79765. return this._influence;
  79766. },
  79767. set: function (influence) {
  79768. if (this._influence === influence) {
  79769. return;
  79770. }
  79771. var previous = this._influence;
  79772. this._influence = influence;
  79773. if (this.onInfluenceChanged.hasObservers) {
  79774. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  79775. }
  79776. },
  79777. enumerable: true,
  79778. configurable: true
  79779. });
  79780. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  79781. get: function () {
  79782. return !!this._positions;
  79783. },
  79784. enumerable: true,
  79785. configurable: true
  79786. });
  79787. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  79788. get: function () {
  79789. return !!this._normals;
  79790. },
  79791. enumerable: true,
  79792. configurable: true
  79793. });
  79794. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  79795. get: function () {
  79796. return !!this._tangents;
  79797. },
  79798. enumerable: true,
  79799. configurable: true
  79800. });
  79801. MorphTarget.prototype.setPositions = function (data) {
  79802. this._positions = data;
  79803. };
  79804. MorphTarget.prototype.getPositions = function () {
  79805. return this._positions;
  79806. };
  79807. MorphTarget.prototype.setNormals = function (data) {
  79808. this._normals = data;
  79809. };
  79810. MorphTarget.prototype.getNormals = function () {
  79811. return this._normals;
  79812. };
  79813. MorphTarget.prototype.setTangents = function (data) {
  79814. this._tangents = data;
  79815. };
  79816. MorphTarget.prototype.getTangents = function () {
  79817. return this._tangents;
  79818. };
  79819. /**
  79820. * Serializes the current target into a Serialization object.
  79821. * Returns the serialized object.
  79822. */
  79823. MorphTarget.prototype.serialize = function () {
  79824. var serializationObject = {};
  79825. serializationObject.name = this.name;
  79826. serializationObject.influence = this.influence;
  79827. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  79828. if (this.hasNormals) {
  79829. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  79830. }
  79831. if (this.hasTangents) {
  79832. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  79833. }
  79834. // Animations
  79835. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  79836. return serializationObject;
  79837. };
  79838. // Statics
  79839. MorphTarget.Parse = function (serializationObject) {
  79840. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  79841. result.setPositions(serializationObject.positions);
  79842. if (serializationObject.normals) {
  79843. result.setNormals(serializationObject.normals);
  79844. }
  79845. if (serializationObject.tangents) {
  79846. result.setTangents(serializationObject.tangents);
  79847. }
  79848. // Animations
  79849. if (serializationObject.animations) {
  79850. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  79851. var parsedAnimation = serializationObject.animations[animationIndex];
  79852. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  79853. }
  79854. }
  79855. return result;
  79856. };
  79857. MorphTarget.FromMesh = function (mesh, name, influence) {
  79858. if (!name) {
  79859. name = mesh.name;
  79860. }
  79861. var result = new MorphTarget(name, influence);
  79862. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79863. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  79864. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  79865. }
  79866. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  79867. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  79868. }
  79869. return result;
  79870. };
  79871. return MorphTarget;
  79872. }());
  79873. BABYLON.MorphTarget = MorphTarget;
  79874. })(BABYLON || (BABYLON = {}));
  79875. //# sourceMappingURL=babylon.morphTarget.js.map
  79876. var BABYLON;
  79877. (function (BABYLON) {
  79878. var MorphTargetManager = /** @class */ (function () {
  79879. function MorphTargetManager(scene) {
  79880. if (scene === void 0) { scene = null; }
  79881. this._targets = new Array();
  79882. this._targetObservable = new Array();
  79883. this._activeTargets = new BABYLON.SmartArray(16);
  79884. this._supportsNormals = false;
  79885. this._supportsTangents = false;
  79886. this._vertexCount = 0;
  79887. this._uniqueId = 0;
  79888. this._tempInfluences = new Array();
  79889. if (!scene) {
  79890. scene = BABYLON.Engine.LastCreatedScene;
  79891. }
  79892. this._scene = scene;
  79893. if (this._scene) {
  79894. this._scene.morphTargetManagers.push(this);
  79895. this._uniqueId = this._scene.getUniqueId();
  79896. }
  79897. }
  79898. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  79899. get: function () {
  79900. return this._uniqueId;
  79901. },
  79902. enumerable: true,
  79903. configurable: true
  79904. });
  79905. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  79906. get: function () {
  79907. return this._vertexCount;
  79908. },
  79909. enumerable: true,
  79910. configurable: true
  79911. });
  79912. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  79913. get: function () {
  79914. return this._supportsNormals;
  79915. },
  79916. enumerable: true,
  79917. configurable: true
  79918. });
  79919. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  79920. get: function () {
  79921. return this._supportsTangents;
  79922. },
  79923. enumerable: true,
  79924. configurable: true
  79925. });
  79926. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  79927. get: function () {
  79928. return this._targets.length;
  79929. },
  79930. enumerable: true,
  79931. configurable: true
  79932. });
  79933. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  79934. get: function () {
  79935. return this._activeTargets.length;
  79936. },
  79937. enumerable: true,
  79938. configurable: true
  79939. });
  79940. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  79941. get: function () {
  79942. return this._influences;
  79943. },
  79944. enumerable: true,
  79945. configurable: true
  79946. });
  79947. MorphTargetManager.prototype.getActiveTarget = function (index) {
  79948. return this._activeTargets.data[index];
  79949. };
  79950. MorphTargetManager.prototype.getTarget = function (index) {
  79951. return this._targets[index];
  79952. };
  79953. MorphTargetManager.prototype.addTarget = function (target) {
  79954. var _this = this;
  79955. this._targets.push(target);
  79956. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  79957. _this._syncActiveTargets(needUpdate);
  79958. }));
  79959. this._syncActiveTargets(true);
  79960. };
  79961. MorphTargetManager.prototype.removeTarget = function (target) {
  79962. var index = this._targets.indexOf(target);
  79963. if (index >= 0) {
  79964. this._targets.splice(index, 1);
  79965. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  79966. this._syncActiveTargets(true);
  79967. }
  79968. };
  79969. /**
  79970. * Serializes the current manager into a Serialization object.
  79971. * Returns the serialized object.
  79972. */
  79973. MorphTargetManager.prototype.serialize = function () {
  79974. var serializationObject = {};
  79975. serializationObject.id = this.uniqueId;
  79976. serializationObject.targets = [];
  79977. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79978. var target = _a[_i];
  79979. serializationObject.targets.push(target.serialize());
  79980. }
  79981. return serializationObject;
  79982. };
  79983. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  79984. var influenceCount = 0;
  79985. this._activeTargets.reset();
  79986. this._supportsNormals = true;
  79987. this._supportsTangents = true;
  79988. this._vertexCount = 0;
  79989. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79990. var target = _a[_i];
  79991. this._activeTargets.push(target);
  79992. this._tempInfluences[influenceCount++] = target.influence;
  79993. var positions = target.getPositions();
  79994. if (positions) {
  79995. this._supportsNormals = this._supportsNormals && target.hasNormals;
  79996. this._supportsTangents = this._supportsTangents && target.hasTangents;
  79997. var vertexCount = positions.length / 3;
  79998. if (this._vertexCount === 0) {
  79999. this._vertexCount = vertexCount;
  80000. }
  80001. else if (this._vertexCount !== vertexCount) {
  80002. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  80003. return;
  80004. }
  80005. }
  80006. }
  80007. if (!this._influences || this._influences.length !== influenceCount) {
  80008. this._influences = new Float32Array(influenceCount);
  80009. }
  80010. for (var index = 0; index < influenceCount; index++) {
  80011. this._influences[index] = this._tempInfluences[index];
  80012. }
  80013. if (needUpdate && this._scene) {
  80014. // Flag meshes as dirty to resync with the active targets
  80015. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  80016. var mesh = _c[_b];
  80017. if (mesh.morphTargetManager === this) {
  80018. mesh._syncGeometryWithMorphTargetManager();
  80019. }
  80020. }
  80021. }
  80022. };
  80023. // Statics
  80024. MorphTargetManager.Parse = function (serializationObject, scene) {
  80025. var result = new MorphTargetManager(scene);
  80026. result._uniqueId = serializationObject.id;
  80027. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  80028. var targetData = _a[_i];
  80029. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  80030. }
  80031. return result;
  80032. };
  80033. return MorphTargetManager;
  80034. }());
  80035. BABYLON.MorphTargetManager = MorphTargetManager;
  80036. })(BABYLON || (BABYLON = {}));
  80037. //# sourceMappingURL=babylon.morphTargetManager.js.map
  80038. var BABYLON;
  80039. (function (BABYLON) {
  80040. var Octree = /** @class */ (function () {
  80041. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  80042. if (maxDepth === void 0) { maxDepth = 2; }
  80043. this.maxDepth = maxDepth;
  80044. this.dynamicContent = new Array();
  80045. this._maxBlockCapacity = maxBlockCapacity || 64;
  80046. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  80047. this._creationFunc = creationFunc;
  80048. }
  80049. // Methods
  80050. Octree.prototype.update = function (worldMin, worldMax, entries) {
  80051. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  80052. };
  80053. Octree.prototype.addMesh = function (entry) {
  80054. for (var index = 0; index < this.blocks.length; index++) {
  80055. var block = this.blocks[index];
  80056. block.addEntry(entry);
  80057. }
  80058. };
  80059. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  80060. this._selectionContent.reset();
  80061. for (var index = 0; index < this.blocks.length; index++) {
  80062. var block = this.blocks[index];
  80063. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  80064. }
  80065. if (allowDuplicate) {
  80066. this._selectionContent.concat(this.dynamicContent);
  80067. }
  80068. else {
  80069. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80070. }
  80071. return this._selectionContent;
  80072. };
  80073. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  80074. this._selectionContent.reset();
  80075. for (var index = 0; index < this.blocks.length; index++) {
  80076. var block = this.blocks[index];
  80077. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  80078. }
  80079. if (allowDuplicate) {
  80080. this._selectionContent.concat(this.dynamicContent);
  80081. }
  80082. else {
  80083. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80084. }
  80085. return this._selectionContent;
  80086. };
  80087. Octree.prototype.intersectsRay = function (ray) {
  80088. this._selectionContent.reset();
  80089. for (var index = 0; index < this.blocks.length; index++) {
  80090. var block = this.blocks[index];
  80091. block.intersectsRay(ray, this._selectionContent);
  80092. }
  80093. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80094. return this._selectionContent;
  80095. };
  80096. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  80097. target.blocks = new Array();
  80098. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  80099. // Segmenting space
  80100. for (var x = 0; x < 2; x++) {
  80101. for (var y = 0; y < 2; y++) {
  80102. for (var z = 0; z < 2; z++) {
  80103. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  80104. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  80105. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  80106. block.addEntries(entries);
  80107. target.blocks.push(block);
  80108. }
  80109. }
  80110. }
  80111. };
  80112. Octree.CreationFuncForMeshes = function (entry, block) {
  80113. var boundingInfo = entry.getBoundingInfo();
  80114. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80115. block.entries.push(entry);
  80116. }
  80117. };
  80118. Octree.CreationFuncForSubMeshes = function (entry, block) {
  80119. var boundingInfo = entry.getBoundingInfo();
  80120. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80121. block.entries.push(entry);
  80122. }
  80123. };
  80124. return Octree;
  80125. }());
  80126. BABYLON.Octree = Octree;
  80127. })(BABYLON || (BABYLON = {}));
  80128. //# sourceMappingURL=babylon.octree.js.map
  80129. var BABYLON;
  80130. (function (BABYLON) {
  80131. var OctreeBlock = /** @class */ (function () {
  80132. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  80133. this.entries = new Array();
  80134. this._boundingVectors = new Array();
  80135. this._capacity = capacity;
  80136. this._depth = depth;
  80137. this._maxDepth = maxDepth;
  80138. this._creationFunc = creationFunc;
  80139. this._minPoint = minPoint;
  80140. this._maxPoint = maxPoint;
  80141. this._boundingVectors.push(minPoint.clone());
  80142. this._boundingVectors.push(maxPoint.clone());
  80143. this._boundingVectors.push(minPoint.clone());
  80144. this._boundingVectors[2].x = maxPoint.x;
  80145. this._boundingVectors.push(minPoint.clone());
  80146. this._boundingVectors[3].y = maxPoint.y;
  80147. this._boundingVectors.push(minPoint.clone());
  80148. this._boundingVectors[4].z = maxPoint.z;
  80149. this._boundingVectors.push(maxPoint.clone());
  80150. this._boundingVectors[5].z = minPoint.z;
  80151. this._boundingVectors.push(maxPoint.clone());
  80152. this._boundingVectors[6].x = minPoint.x;
  80153. this._boundingVectors.push(maxPoint.clone());
  80154. this._boundingVectors[7].y = minPoint.y;
  80155. }
  80156. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  80157. // Property
  80158. get: function () {
  80159. return this._capacity;
  80160. },
  80161. enumerable: true,
  80162. configurable: true
  80163. });
  80164. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  80165. get: function () {
  80166. return this._minPoint;
  80167. },
  80168. enumerable: true,
  80169. configurable: true
  80170. });
  80171. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  80172. get: function () {
  80173. return this._maxPoint;
  80174. },
  80175. enumerable: true,
  80176. configurable: true
  80177. });
  80178. // Methods
  80179. OctreeBlock.prototype.addEntry = function (entry) {
  80180. if (this.blocks) {
  80181. for (var index = 0; index < this.blocks.length; index++) {
  80182. var block = this.blocks[index];
  80183. block.addEntry(entry);
  80184. }
  80185. return;
  80186. }
  80187. this._creationFunc(entry, this);
  80188. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  80189. this.createInnerBlocks();
  80190. }
  80191. };
  80192. OctreeBlock.prototype.addEntries = function (entries) {
  80193. for (var index = 0; index < entries.length; index++) {
  80194. var mesh = entries[index];
  80195. this.addEntry(mesh);
  80196. }
  80197. };
  80198. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  80199. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  80200. if (this.blocks) {
  80201. for (var index = 0; index < this.blocks.length; index++) {
  80202. var block = this.blocks[index];
  80203. block.select(frustumPlanes, selection, allowDuplicate);
  80204. }
  80205. return;
  80206. }
  80207. if (allowDuplicate) {
  80208. selection.concat(this.entries);
  80209. }
  80210. else {
  80211. selection.concatWithNoDuplicate(this.entries);
  80212. }
  80213. }
  80214. };
  80215. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  80216. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  80217. if (this.blocks) {
  80218. for (var index = 0; index < this.blocks.length; index++) {
  80219. var block = this.blocks[index];
  80220. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  80221. }
  80222. return;
  80223. }
  80224. if (allowDuplicate) {
  80225. selection.concat(this.entries);
  80226. }
  80227. else {
  80228. selection.concatWithNoDuplicate(this.entries);
  80229. }
  80230. }
  80231. };
  80232. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  80233. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  80234. if (this.blocks) {
  80235. for (var index = 0; index < this.blocks.length; index++) {
  80236. var block = this.blocks[index];
  80237. block.intersectsRay(ray, selection);
  80238. }
  80239. return;
  80240. }
  80241. selection.concatWithNoDuplicate(this.entries);
  80242. }
  80243. };
  80244. OctreeBlock.prototype.createInnerBlocks = function () {
  80245. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  80246. };
  80247. return OctreeBlock;
  80248. }());
  80249. BABYLON.OctreeBlock = OctreeBlock;
  80250. })(BABYLON || (BABYLON = {}));
  80251. //# sourceMappingURL=babylon.octreeBlock.js.map
  80252. var BABYLON;
  80253. (function (BABYLON) {
  80254. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  80255. __extends(VRDistortionCorrectionPostProcess, _super);
  80256. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  80257. var _this = _super.call(this, name, "vrDistortionCorrection", [
  80258. 'LensCenter',
  80259. 'Scale',
  80260. 'ScaleIn',
  80261. 'HmdWarpParam'
  80262. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  80263. _this._isRightEye = isRightEye;
  80264. _this._distortionFactors = vrMetrics.distortionK;
  80265. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  80266. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  80267. _this.adaptScaleToCurrentViewport = true;
  80268. _this.onSizeChangedObservable.add(function () {
  80269. _this.aspectRatio = _this.width * .5 / _this.height;
  80270. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  80271. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  80272. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  80273. });
  80274. _this.onApplyObservable.add(function (effect) {
  80275. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  80276. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  80277. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  80278. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  80279. });
  80280. return _this;
  80281. }
  80282. return VRDistortionCorrectionPostProcess;
  80283. }(BABYLON.PostProcess));
  80284. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  80285. })(BABYLON || (BABYLON = {}));
  80286. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  80287. var BABYLON;
  80288. (function (BABYLON) {
  80289. var AnaglyphPostProcess = /** @class */ (function (_super) {
  80290. __extends(AnaglyphPostProcess, _super);
  80291. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  80292. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  80293. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80294. _this.onApplyObservable.add(function (effect) {
  80295. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  80296. });
  80297. return _this;
  80298. }
  80299. return AnaglyphPostProcess;
  80300. }(BABYLON.PostProcess));
  80301. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  80302. })(BABYLON || (BABYLON = {}));
  80303. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  80304. var BABYLON;
  80305. (function (BABYLON) {
  80306. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  80307. __extends(StereoscopicInterlacePostProcess, _super);
  80308. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  80309. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  80310. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80311. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80312. _this.onSizeChangedObservable.add(function () {
  80313. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80314. });
  80315. _this.onApplyObservable.add(function (effect) {
  80316. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  80317. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  80318. });
  80319. return _this;
  80320. }
  80321. return StereoscopicInterlacePostProcess;
  80322. }(BABYLON.PostProcess));
  80323. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  80324. })(BABYLON || (BABYLON = {}));
  80325. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  80326. var BABYLON;
  80327. (function (BABYLON) {
  80328. /**
  80329. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  80330. * Screen rotation is taken into account.
  80331. */
  80332. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  80333. function FreeCameraDeviceOrientationInput() {
  80334. var _this = this;
  80335. this._screenOrientationAngle = 0;
  80336. this._screenQuaternion = new BABYLON.Quaternion();
  80337. this._alpha = 0;
  80338. this._beta = 0;
  80339. this._gamma = 0;
  80340. this._orientationChanged = function () {
  80341. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  80342. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  80343. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  80344. };
  80345. this._deviceOrientation = function (evt) {
  80346. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  80347. _this._beta = evt.beta !== null ? evt.beta : 0;
  80348. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  80349. };
  80350. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  80351. this._orientationChanged();
  80352. }
  80353. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  80354. get: function () {
  80355. return this._camera;
  80356. },
  80357. set: function (camera) {
  80358. this._camera = camera;
  80359. if (this._camera != null && !this._camera.rotationQuaternion) {
  80360. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  80361. }
  80362. },
  80363. enumerable: true,
  80364. configurable: true
  80365. });
  80366. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80367. window.addEventListener("orientationchange", this._orientationChanged);
  80368. window.addEventListener("deviceorientation", this._deviceOrientation);
  80369. //In certain cases, the attach control is called AFTER orientation was changed,
  80370. //So this is needed.
  80371. this._orientationChanged();
  80372. };
  80373. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  80374. window.removeEventListener("orientationchange", this._orientationChanged);
  80375. window.removeEventListener("deviceorientation", this._deviceOrientation);
  80376. };
  80377. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  80378. //if no device orientation provided, don't update the rotation.
  80379. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  80380. if (!this._alpha)
  80381. return;
  80382. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  80383. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  80384. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  80385. //Mirror on XY Plane
  80386. this._camera.rotationQuaternion.z *= -1;
  80387. this._camera.rotationQuaternion.w *= -1;
  80388. };
  80389. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  80390. return "FreeCameraDeviceOrientationInput";
  80391. };
  80392. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  80393. return "deviceOrientation";
  80394. };
  80395. return FreeCameraDeviceOrientationInput;
  80396. }());
  80397. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  80398. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  80399. })(BABYLON || (BABYLON = {}));
  80400. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  80401. var BABYLON;
  80402. (function (BABYLON) {
  80403. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  80404. function ArcRotateCameraVRDeviceOrientationInput() {
  80405. this.alphaCorrection = 1;
  80406. this.betaCorrection = 1;
  80407. this.gammaCorrection = 1;
  80408. this._alpha = 0;
  80409. this._gamma = 0;
  80410. this._dirty = false;
  80411. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  80412. }
  80413. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80414. this.camera.attachControl(element, noPreventDefault);
  80415. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  80416. };
  80417. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  80418. if (evt.alpha !== null) {
  80419. this._alpha = +evt.alpha | 0;
  80420. }
  80421. if (evt.gamma !== null) {
  80422. this._gamma = +evt.gamma | 0;
  80423. }
  80424. this._dirty = true;
  80425. };
  80426. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  80427. if (this._dirty) {
  80428. this._dirty = false;
  80429. if (this._gamma < 0) {
  80430. this._gamma = 180 + this._gamma;
  80431. }
  80432. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  80433. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  80434. }
  80435. };
  80436. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  80437. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  80438. };
  80439. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  80440. return "ArcRotateCameraVRDeviceOrientationInput";
  80441. };
  80442. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  80443. return "VRDeviceOrientation";
  80444. };
  80445. return ArcRotateCameraVRDeviceOrientationInput;
  80446. }());
  80447. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  80448. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  80449. })(BABYLON || (BABYLON = {}));
  80450. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  80451. var BABYLON;
  80452. (function (BABYLON) {
  80453. var VRCameraMetrics = /** @class */ (function () {
  80454. function VRCameraMetrics() {
  80455. this.compensateDistortion = true;
  80456. }
  80457. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  80458. get: function () {
  80459. return this.hResolution / (2 * this.vResolution);
  80460. },
  80461. enumerable: true,
  80462. configurable: true
  80463. });
  80464. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  80465. get: function () {
  80466. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  80467. },
  80468. enumerable: true,
  80469. configurable: true
  80470. });
  80471. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  80472. get: function () {
  80473. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80474. var h = (4 * meters) / this.hScreenSize;
  80475. return BABYLON.Matrix.Translation(h, 0, 0);
  80476. },
  80477. enumerable: true,
  80478. configurable: true
  80479. });
  80480. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  80481. get: function () {
  80482. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80483. var h = (4 * meters) / this.hScreenSize;
  80484. return BABYLON.Matrix.Translation(-h, 0, 0);
  80485. },
  80486. enumerable: true,
  80487. configurable: true
  80488. });
  80489. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  80490. get: function () {
  80491. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  80492. },
  80493. enumerable: true,
  80494. configurable: true
  80495. });
  80496. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  80497. get: function () {
  80498. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  80499. },
  80500. enumerable: true,
  80501. configurable: true
  80502. });
  80503. VRCameraMetrics.GetDefault = function () {
  80504. var result = new VRCameraMetrics();
  80505. result.hResolution = 1280;
  80506. result.vResolution = 800;
  80507. result.hScreenSize = 0.149759993;
  80508. result.vScreenSize = 0.0935999975;
  80509. result.vScreenCenter = 0.0467999987;
  80510. result.eyeToScreenDistance = 0.0410000011;
  80511. result.lensSeparationDistance = 0.0635000020;
  80512. result.interpupillaryDistance = 0.0640000030;
  80513. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  80514. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  80515. result.postProcessScaleFactor = 1.714605507808412;
  80516. result.lensCenterOffset = 0.151976421;
  80517. return result;
  80518. };
  80519. return VRCameraMetrics;
  80520. }());
  80521. BABYLON.VRCameraMetrics = VRCameraMetrics;
  80522. })(BABYLON || (BABYLON = {}));
  80523. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  80524. var BABYLON;
  80525. (function (BABYLON) {
  80526. /**
  80527. * This represents a WebVR camera.
  80528. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  80529. * @example http://doc.babylonjs.com/how_to/webvr_camera
  80530. */
  80531. var WebVRFreeCamera = /** @class */ (function (_super) {
  80532. __extends(WebVRFreeCamera, _super);
  80533. /**
  80534. * Instantiates a WebVRFreeCamera.
  80535. * @param name The name of the WebVRFreeCamera
  80536. * @param position The starting anchor position for the camera
  80537. * @param scene The scene the camera belongs to
  80538. * @param webVROptions a set of customizable options for the webVRCamera
  80539. */
  80540. function WebVRFreeCamera(name, position, scene, webVROptions) {
  80541. if (webVROptions === void 0) { webVROptions = {}; }
  80542. var _this = _super.call(this, name, position, scene) || this;
  80543. _this.webVROptions = webVROptions;
  80544. /**
  80545. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  80546. */
  80547. _this._vrDevice = null;
  80548. /**
  80549. * The rawPose of the vrDevice.
  80550. */
  80551. _this.rawPose = null;
  80552. _this._specsVersion = "1.1";
  80553. _this._attached = false;
  80554. _this._descendants = [];
  80555. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80556. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80557. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  80558. _this._standingMatrix = null;
  80559. /**
  80560. * Represents device position in babylon space.
  80561. */
  80562. _this.devicePosition = BABYLON.Vector3.Zero();
  80563. /**
  80564. * Represents device rotation in babylon space.
  80565. */
  80566. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  80567. /**
  80568. * The scale of the device to be used when translating from device space to babylon space.
  80569. */
  80570. _this.deviceScaleFactor = 1;
  80571. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80572. _this._worldToDevice = BABYLON.Matrix.Identity();
  80573. /**
  80574. * References to the webVR controllers for the vrDevice.
  80575. */
  80576. _this.controllers = [];
  80577. /**
  80578. * Emits an event when a controller is attached.
  80579. */
  80580. _this.onControllersAttachedObservable = new BABYLON.Observable();
  80581. /**
  80582. * Emits an event when a controller's mesh has been loaded;
  80583. */
  80584. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80585. /**
  80586. * If the rig cameras be used as parent instead of this camera.
  80587. */
  80588. _this.rigParenting = true;
  80589. _this._defaultHeight = undefined;
  80590. _this._workingVector = BABYLON.Vector3.Zero();
  80591. _this._oneVector = BABYLON.Vector3.One();
  80592. _this._workingMatrix = BABYLON.Matrix.Identity();
  80593. _this._cache.position = BABYLON.Vector3.Zero();
  80594. if (webVROptions.defaultHeight) {
  80595. _this._defaultHeight = webVROptions.defaultHeight;
  80596. _this.position.y = _this._defaultHeight;
  80597. }
  80598. _this.minZ = 0.1;
  80599. //legacy support - the compensation boolean was removed.
  80600. if (arguments.length === 5) {
  80601. _this.webVROptions = arguments[4];
  80602. }
  80603. // default webVR options
  80604. if (_this.webVROptions.trackPosition == undefined) {
  80605. _this.webVROptions.trackPosition = true;
  80606. }
  80607. if (_this.webVROptions.controllerMeshes == undefined) {
  80608. _this.webVROptions.controllerMeshes = true;
  80609. }
  80610. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  80611. _this.webVROptions.defaultLightingOnControllers = true;
  80612. }
  80613. _this.rotationQuaternion = new BABYLON.Quaternion();
  80614. if (_this.webVROptions && _this.webVROptions.positionScale) {
  80615. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  80616. }
  80617. //enable VR
  80618. var engine = _this.getEngine();
  80619. _this._onVREnabled = function (success) { if (success) {
  80620. _this.initControllers();
  80621. } };
  80622. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  80623. engine.initWebVR().add(function (event) {
  80624. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  80625. return;
  80626. }
  80627. _this._vrDevice = event.vrDisplay;
  80628. //reset the rig parameters.
  80629. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  80630. if (_this._attached) {
  80631. _this.getEngine().enableVR();
  80632. }
  80633. });
  80634. if (typeof (VRFrameData) !== "undefined")
  80635. _this._frameData = new VRFrameData();
  80636. /**
  80637. * The idea behind the following lines:
  80638. * objects that have the camera as parent should actually have the rig cameras as a parent.
  80639. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  80640. * the second will not show it correctly.
  80641. *
  80642. * To solve this - each object that has the camera as parent will be added to a protected array.
  80643. * When the rig camera renders, it will take this array and set all of those to be its children.
  80644. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  80645. * Amazing!
  80646. */
  80647. scene.onBeforeCameraRenderObservable.add(function (camera) {
  80648. if (camera.parent === _this && _this.rigParenting) {
  80649. _this._descendants = _this.getDescendants(true, function (n) {
  80650. // don't take the cameras or the controllers!
  80651. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  80652. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  80653. return !isController && !isRigCamera;
  80654. });
  80655. _this._descendants.forEach(function (node) {
  80656. node.parent = camera;
  80657. });
  80658. }
  80659. });
  80660. scene.onAfterCameraRenderObservable.add(function (camera) {
  80661. if (camera.parent === _this && _this.rigParenting) {
  80662. _this._descendants.forEach(function (node) {
  80663. node.parent = _this;
  80664. });
  80665. }
  80666. });
  80667. return _this;
  80668. }
  80669. /**
  80670. * Gets the device distance from the ground in meters.
  80671. * @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.
  80672. */
  80673. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  80674. if (this._standingMatrix) {
  80675. // Add standing matrix offset to get real offset from ground in room
  80676. this._standingMatrix.getTranslationToRef(this._workingVector);
  80677. return this._deviceRoomPosition.y + this._workingVector.y;
  80678. }
  80679. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  80680. return this._defaultHeight || 0;
  80681. };
  80682. /**
  80683. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80684. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  80685. */
  80686. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  80687. var _this = this;
  80688. if (callback === void 0) { callback = function (bool) { }; }
  80689. // Use standing matrix if available
  80690. this.getEngine().initWebVRAsync().then(function (result) {
  80691. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  80692. callback(false);
  80693. }
  80694. else {
  80695. _this._standingMatrix = new BABYLON.Matrix();
  80696. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  80697. if (!_this.getScene().useRightHandedSystem) {
  80698. [2, 6, 8, 9, 14].forEach(function (num) {
  80699. if (_this._standingMatrix) {
  80700. _this._standingMatrix.m[num] *= -1;
  80701. }
  80702. });
  80703. }
  80704. callback(true);
  80705. }
  80706. });
  80707. };
  80708. /**
  80709. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80710. * @returns A promise with a boolean set to if the standing matrix is supported.
  80711. */
  80712. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  80713. var _this = this;
  80714. return new Promise(function (res, rej) {
  80715. _this.useStandingMatrix(function (supported) {
  80716. res(supported);
  80717. });
  80718. });
  80719. };
  80720. /**
  80721. * Disposes the camera
  80722. */
  80723. WebVRFreeCamera.prototype.dispose = function () {
  80724. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  80725. _super.prototype.dispose.call(this);
  80726. };
  80727. /**
  80728. * Gets a vrController by name.
  80729. * @param name The name of the controller to retreive
  80730. * @returns the controller matching the name specified or null if not found
  80731. */
  80732. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  80733. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  80734. var gp = _a[_i];
  80735. if (gp.hand === name) {
  80736. return gp;
  80737. }
  80738. }
  80739. return null;
  80740. };
  80741. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  80742. /**
  80743. * The controller corrisponding to the users left hand.
  80744. */
  80745. get: function () {
  80746. if (!this._leftController) {
  80747. this._leftController = this.getControllerByName("left");
  80748. }
  80749. return this._leftController;
  80750. },
  80751. enumerable: true,
  80752. configurable: true
  80753. });
  80754. ;
  80755. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  80756. /**
  80757. * The controller corrisponding to the users right hand.
  80758. */
  80759. get: function () {
  80760. if (!this._rightController) {
  80761. this._rightController = this.getControllerByName("right");
  80762. }
  80763. return this._rightController;
  80764. },
  80765. enumerable: true,
  80766. configurable: true
  80767. });
  80768. ;
  80769. /**
  80770. * Casts a ray forward from the vrCamera's gaze.
  80771. * @param length Length of the ray (default: 100)
  80772. * @returns the ray corrisponding to the gaze
  80773. */
  80774. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  80775. if (length === void 0) { length = 100; }
  80776. if (this.leftCamera) {
  80777. // Use left eye to avoid computation to compute center on every call
  80778. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  80779. }
  80780. else {
  80781. return _super.prototype.getForwardRay.call(this, length);
  80782. }
  80783. };
  80784. /**
  80785. * Updates the camera based on device's frame data
  80786. */
  80787. WebVRFreeCamera.prototype._checkInputs = function () {
  80788. if (this._vrDevice && this._vrDevice.isPresenting) {
  80789. this._vrDevice.getFrameData(this._frameData);
  80790. this.updateFromDevice(this._frameData.pose);
  80791. }
  80792. _super.prototype._checkInputs.call(this);
  80793. };
  80794. /**
  80795. * Updates the poseControlled values based on the input device pose.
  80796. * @param poseData Pose coming from the device
  80797. */
  80798. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  80799. if (poseData && poseData.orientation) {
  80800. this.rawPose = poseData;
  80801. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  80802. if (this.getScene().useRightHandedSystem) {
  80803. this._deviceRoomRotationQuaternion.z *= -1;
  80804. this._deviceRoomRotationQuaternion.w *= -1;
  80805. }
  80806. if (this.webVROptions.trackPosition && this.rawPose.position) {
  80807. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  80808. if (this.getScene().useRightHandedSystem) {
  80809. this._deviceRoomPosition.z *= -1;
  80810. }
  80811. }
  80812. }
  80813. };
  80814. /**
  80815. * WebVR's attach control will start broadcasting frames to the device.
  80816. * Note that in certain browsers (chrome for example) this function must be called
  80817. * within a user-interaction callback. Example:
  80818. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  80819. *
  80820. * @param element html element to attach the vrDevice to
  80821. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  80822. */
  80823. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  80824. _super.prototype.attachControl.call(this, element, noPreventDefault);
  80825. this._attached = true;
  80826. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  80827. if (this._vrDevice) {
  80828. this.getEngine().enableVR();
  80829. }
  80830. };
  80831. /**
  80832. * Detaches the camera from the html element and disables VR
  80833. *
  80834. * @param element html element to detach from
  80835. */
  80836. WebVRFreeCamera.prototype.detachControl = function (element) {
  80837. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80838. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80839. _super.prototype.detachControl.call(this, element);
  80840. this._attached = false;
  80841. this.getEngine().disableVR();
  80842. };
  80843. /**
  80844. * @returns the name of this class
  80845. */
  80846. WebVRFreeCamera.prototype.getClassName = function () {
  80847. return "WebVRFreeCamera";
  80848. };
  80849. /**
  80850. * Calls resetPose on the vrDisplay
  80851. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  80852. */
  80853. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  80854. //uses the vrDisplay's "resetPose()".
  80855. //pitch and roll won't be affected.
  80856. this._vrDevice.resetPose();
  80857. };
  80858. /**
  80859. * Updates the rig cameras (left and right eye)
  80860. */
  80861. WebVRFreeCamera.prototype._updateRigCameras = function () {
  80862. var camLeft = this._rigCameras[0];
  80863. var camRight = this._rigCameras[1];
  80864. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80865. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80866. camLeft.position.copyFrom(this._deviceRoomPosition);
  80867. camRight.position.copyFrom(this._deviceRoomPosition);
  80868. };
  80869. /**
  80870. * Updates the cached values of the camera
  80871. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  80872. */
  80873. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  80874. var _this = this;
  80875. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  80876. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  80877. if (!this.updateCacheCalled) {
  80878. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  80879. this.updateCacheCalled = true;
  80880. this.update();
  80881. }
  80882. // Set working vector to the device position in room space rotated by the new rotation
  80883. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  80884. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  80885. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  80886. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  80887. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  80888. // Add translation from anchor position
  80889. this._deviceToWorld.getTranslationToRef(this._workingVector);
  80890. this._workingVector.addInPlace(this.position);
  80891. this._workingVector.subtractInPlace(this._cache.position);
  80892. this._deviceToWorld.setTranslation(this._workingVector);
  80893. // Set an inverted matrix to be used when updating the camera
  80894. this._deviceToWorld.invertToRef(this._worldToDevice);
  80895. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  80896. this.controllers.forEach(function (controller) {
  80897. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  80898. controller.update();
  80899. });
  80900. }
  80901. if (!ignoreParentClass) {
  80902. _super.prototype._updateCache.call(this);
  80903. }
  80904. this.updateCacheCalled = false;
  80905. };
  80906. /**
  80907. * Updates the current device position and rotation in the babylon world
  80908. */
  80909. WebVRFreeCamera.prototype.update = function () {
  80910. // Get current device position in babylon world
  80911. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  80912. // Get current device rotation in babylon world
  80913. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  80914. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  80915. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80916. _super.prototype.update.call(this);
  80917. };
  80918. /**
  80919. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  80920. * @returns an identity matrix
  80921. */
  80922. WebVRFreeCamera.prototype._getViewMatrix = function () {
  80923. return BABYLON.Matrix.Identity();
  80924. };
  80925. /**
  80926. * This function is called by the two RIG cameras.
  80927. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  80928. */
  80929. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  80930. var _this = this;
  80931. // Update the parent camera prior to using a child camera to avoid desynchronization
  80932. var parentCamera = this._cameraRigParams["parentCamera"];
  80933. parentCamera._updateCache();
  80934. //WebVR 1.1
  80935. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  80936. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  80937. if (!this.getScene().useRightHandedSystem) {
  80938. [2, 6, 8, 9, 14].forEach(function (num) {
  80939. _this._webvrViewMatrix.m[num] *= -1;
  80940. });
  80941. }
  80942. // update the camera rotation matrix
  80943. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  80944. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  80945. // Computing target and final matrix
  80946. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  80947. // should the view matrix be updated with scale and position offset?
  80948. if (parentCamera.deviceScaleFactor !== 1) {
  80949. this._webvrViewMatrix.invert();
  80950. // scale the position, if set
  80951. if (parentCamera.deviceScaleFactor) {
  80952. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  80953. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  80954. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  80955. }
  80956. this._webvrViewMatrix.invert();
  80957. }
  80958. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  80959. return this._webvrViewMatrix;
  80960. };
  80961. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  80962. var _this = this;
  80963. var parentCamera = this.parent;
  80964. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  80965. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  80966. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  80967. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  80968. //babylon compatible matrix
  80969. if (!this.getScene().useRightHandedSystem) {
  80970. [8, 9, 10, 11].forEach(function (num) {
  80971. _this._projectionMatrix.m[num] *= -1;
  80972. });
  80973. }
  80974. return this._projectionMatrix;
  80975. };
  80976. /**
  80977. * Initializes the controllers and their meshes
  80978. */
  80979. WebVRFreeCamera.prototype.initControllers = function () {
  80980. var _this = this;
  80981. this.controllers = [];
  80982. var manager = this.getScene().gamepadManager;
  80983. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80984. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80985. var webVrController = gamepad;
  80986. if (webVrController.defaultModel) {
  80987. webVrController.defaultModel.setEnabled(false);
  80988. }
  80989. if (webVrController.hand === "right") {
  80990. _this._rightController = null;
  80991. }
  80992. if (webVrController.hand === "left") {
  80993. _this._leftController = null;
  80994. }
  80995. var controllerIndex = _this.controllers.indexOf(webVrController);
  80996. if (controllerIndex !== -1) {
  80997. _this.controllers.splice(controllerIndex, 1);
  80998. }
  80999. }
  81000. });
  81001. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81002. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81003. var webVrController_1 = gamepad;
  81004. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  81005. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  81006. if (_this.webVROptions.controllerMeshes) {
  81007. if (webVrController_1.defaultModel) {
  81008. webVrController_1.defaultModel.setEnabled(true);
  81009. }
  81010. else {
  81011. // Load the meshes
  81012. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  81013. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  81014. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  81015. if (_this.webVROptions.defaultLightingOnControllers) {
  81016. if (!_this._lightOnControllers) {
  81017. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  81018. }
  81019. var activateLightOnSubMeshes_1 = function (mesh, light) {
  81020. var children = mesh.getChildren();
  81021. if (children.length !== 0) {
  81022. children.forEach(function (mesh) {
  81023. light.includedOnlyMeshes.push(mesh);
  81024. activateLightOnSubMeshes_1(mesh, light);
  81025. });
  81026. }
  81027. };
  81028. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  81029. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  81030. }
  81031. });
  81032. }
  81033. }
  81034. webVrController_1.attachToPoseControlledCamera(_this);
  81035. // since this is async - sanity check. Is the controller already stored?
  81036. if (_this.controllers.indexOf(webVrController_1) === -1) {
  81037. //add to the controllers array
  81038. _this.controllers.push(webVrController_1);
  81039. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  81040. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  81041. // So we're overriding setting left & right manually to be sure
  81042. var firstViveWandDetected = false;
  81043. for (var i = 0; i < _this.controllers.length; i++) {
  81044. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81045. if (!firstViveWandDetected) {
  81046. firstViveWandDetected = true;
  81047. _this.controllers[i].hand = "left";
  81048. }
  81049. else {
  81050. _this.controllers[i].hand = "right";
  81051. }
  81052. }
  81053. }
  81054. //did we find enough controllers? Great! let the developer know.
  81055. if (_this.controllers.length >= 2) {
  81056. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  81057. }
  81058. }
  81059. }
  81060. });
  81061. };
  81062. return WebVRFreeCamera;
  81063. }(BABYLON.FreeCamera));
  81064. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  81065. })(BABYLON || (BABYLON = {}));
  81066. //# sourceMappingURL=babylon.webVRCamera.js.map
  81067. var BABYLON;
  81068. (function (BABYLON) {
  81069. // We're mainly based on the logic defined into the FreeCamera code
  81070. /**
  81071. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  81072. * being tilted forward or back and left or right.
  81073. */
  81074. var DeviceOrientationCamera = /** @class */ (function (_super) {
  81075. __extends(DeviceOrientationCamera, _super);
  81076. /**
  81077. * Creates a new device orientation camera. @see DeviceOrientationCamera
  81078. * @param name The name of the camera
  81079. * @param position The start position camera
  81080. * @param scene The scene the camera belongs to
  81081. */
  81082. function DeviceOrientationCamera(name, position, scene) {
  81083. var _this = _super.call(this, name, position, scene) || this;
  81084. _this._quaternionCache = new BABYLON.Quaternion();
  81085. _this.inputs.addDeviceOrientation();
  81086. return _this;
  81087. }
  81088. /**
  81089. * Gets the current instance class name ("DeviceOrientationCamera").
  81090. * This helps avoiding instanceof at run time.
  81091. * @returns the class name
  81092. */
  81093. DeviceOrientationCamera.prototype.getClassName = function () {
  81094. return "DeviceOrientationCamera";
  81095. };
  81096. /**
  81097. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  81098. */
  81099. DeviceOrientationCamera.prototype._checkInputs = function () {
  81100. _super.prototype._checkInputs.call(this);
  81101. this._quaternionCache.copyFrom(this.rotationQuaternion);
  81102. if (this._initialQuaternion) {
  81103. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81104. }
  81105. };
  81106. /**
  81107. * Reset the camera to its default orientation on the specified axis only.
  81108. * @param axis The axis to reset
  81109. */
  81110. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  81111. var _this = this;
  81112. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  81113. //can only work if this camera has a rotation quaternion already.
  81114. if (!this.rotationQuaternion)
  81115. return;
  81116. if (!this._initialQuaternion) {
  81117. this._initialQuaternion = new BABYLON.Quaternion();
  81118. }
  81119. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  81120. ['x', 'y', 'z'].forEach(function (axisName) {
  81121. if (!axis[axisName]) {
  81122. _this._initialQuaternion[axisName] = 0;
  81123. }
  81124. else {
  81125. _this._initialQuaternion[axisName] *= -1;
  81126. }
  81127. });
  81128. this._initialQuaternion.normalize();
  81129. //force rotation update
  81130. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81131. };
  81132. return DeviceOrientationCamera;
  81133. }(BABYLON.FreeCamera));
  81134. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  81135. })(BABYLON || (BABYLON = {}));
  81136. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  81137. var BABYLON;
  81138. (function (BABYLON) {
  81139. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  81140. __extends(VRDeviceOrientationFreeCamera, _super);
  81141. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81142. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81143. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81144. var _this = _super.call(this, name, position, scene) || this;
  81145. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81146. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81147. return _this;
  81148. }
  81149. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  81150. return "VRDeviceOrientationFreeCamera";
  81151. };
  81152. return VRDeviceOrientationFreeCamera;
  81153. }(BABYLON.DeviceOrientationCamera));
  81154. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  81155. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  81156. __extends(VRDeviceOrientationGamepadCamera, _super);
  81157. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81158. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81159. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81160. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  81161. _this.inputs.addGamepad();
  81162. return _this;
  81163. }
  81164. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  81165. return "VRDeviceOrientationGamepadCamera";
  81166. };
  81167. return VRDeviceOrientationGamepadCamera;
  81168. }(VRDeviceOrientationFreeCamera));
  81169. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  81170. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  81171. __extends(VRDeviceOrientationArcRotateCamera, _super);
  81172. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  81173. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81174. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81175. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81176. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81177. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81178. _this.inputs.addVRDeviceOrientation();
  81179. return _this;
  81180. }
  81181. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  81182. return "VRDeviceOrientationArcRotateCamera";
  81183. };
  81184. return VRDeviceOrientationArcRotateCamera;
  81185. }(BABYLON.ArcRotateCamera));
  81186. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  81187. })(BABYLON || (BABYLON = {}));
  81188. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  81189. var BABYLON;
  81190. (function (BABYLON) {
  81191. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  81192. __extends(AnaglyphFreeCamera, _super);
  81193. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  81194. var _this = _super.call(this, name, position, scene) || this;
  81195. _this.interaxialDistance = interaxialDistance;
  81196. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81197. return _this;
  81198. }
  81199. AnaglyphFreeCamera.prototype.getClassName = function () {
  81200. return "AnaglyphFreeCamera";
  81201. };
  81202. return AnaglyphFreeCamera;
  81203. }(BABYLON.FreeCamera));
  81204. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  81205. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  81206. __extends(AnaglyphArcRotateCamera, _super);
  81207. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  81208. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81209. _this.interaxialDistance = interaxialDistance;
  81210. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81211. return _this;
  81212. }
  81213. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  81214. return "AnaglyphArcRotateCamera";
  81215. };
  81216. return AnaglyphArcRotateCamera;
  81217. }(BABYLON.ArcRotateCamera));
  81218. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  81219. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  81220. __extends(AnaglyphGamepadCamera, _super);
  81221. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  81222. var _this = _super.call(this, name, position, scene) || this;
  81223. _this.interaxialDistance = interaxialDistance;
  81224. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81225. return _this;
  81226. }
  81227. AnaglyphGamepadCamera.prototype.getClassName = function () {
  81228. return "AnaglyphGamepadCamera";
  81229. };
  81230. return AnaglyphGamepadCamera;
  81231. }(BABYLON.GamepadCamera));
  81232. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  81233. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  81234. __extends(AnaglyphUniversalCamera, _super);
  81235. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  81236. var _this = _super.call(this, name, position, scene) || this;
  81237. _this.interaxialDistance = interaxialDistance;
  81238. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81239. return _this;
  81240. }
  81241. AnaglyphUniversalCamera.prototype.getClassName = function () {
  81242. return "AnaglyphUniversalCamera";
  81243. };
  81244. return AnaglyphUniversalCamera;
  81245. }(BABYLON.UniversalCamera));
  81246. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  81247. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  81248. __extends(StereoscopicFreeCamera, _super);
  81249. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81250. var _this = _super.call(this, name, position, scene) || this;
  81251. _this.interaxialDistance = interaxialDistance;
  81252. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81253. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81254. return _this;
  81255. }
  81256. StereoscopicFreeCamera.prototype.getClassName = function () {
  81257. return "StereoscopicFreeCamera";
  81258. };
  81259. return StereoscopicFreeCamera;
  81260. }(BABYLON.FreeCamera));
  81261. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  81262. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  81263. __extends(StereoscopicArcRotateCamera, _super);
  81264. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  81265. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81266. _this.interaxialDistance = interaxialDistance;
  81267. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81268. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81269. return _this;
  81270. }
  81271. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  81272. return "StereoscopicArcRotateCamera";
  81273. };
  81274. return StereoscopicArcRotateCamera;
  81275. }(BABYLON.ArcRotateCamera));
  81276. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  81277. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  81278. __extends(StereoscopicGamepadCamera, _super);
  81279. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81280. var _this = _super.call(this, name, position, scene) || this;
  81281. _this.interaxialDistance = interaxialDistance;
  81282. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81283. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81284. return _this;
  81285. }
  81286. StereoscopicGamepadCamera.prototype.getClassName = function () {
  81287. return "StereoscopicGamepadCamera";
  81288. };
  81289. return StereoscopicGamepadCamera;
  81290. }(BABYLON.GamepadCamera));
  81291. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  81292. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  81293. __extends(StereoscopicUniversalCamera, _super);
  81294. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81295. var _this = _super.call(this, name, position, scene) || this;
  81296. _this.interaxialDistance = interaxialDistance;
  81297. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81298. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81299. return _this;
  81300. }
  81301. StereoscopicUniversalCamera.prototype.getClassName = function () {
  81302. return "StereoscopicUniversalCamera";
  81303. };
  81304. return StereoscopicUniversalCamera;
  81305. }(BABYLON.UniversalCamera));
  81306. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  81307. })(BABYLON || (BABYLON = {}));
  81308. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  81309. var BABYLON;
  81310. (function (BABYLON) {
  81311. var VRExperienceHelperGazer = /** @class */ (function () {
  81312. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  81313. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  81314. this.scene = scene;
  81315. this._pointerDownOnMeshAsked = false;
  81316. this._isActionableMesh = false;
  81317. this._teleportationRequestInitiated = false;
  81318. this._teleportationBackRequestInitiated = false;
  81319. this._dpadPressed = true;
  81320. this._activePointer = false;
  81321. this._id = VRExperienceHelperGazer._idCounter++;
  81322. // Gaze tracker
  81323. if (!gazeTrackerToClone) {
  81324. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  81325. this._gazeTracker.bakeCurrentTransformIntoVertices();
  81326. this._gazeTracker.isPickable = false;
  81327. this._gazeTracker.isVisible = false;
  81328. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  81329. targetMat.specularColor = BABYLON.Color3.Black();
  81330. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81331. targetMat.backFaceCulling = false;
  81332. this._gazeTracker.material = targetMat;
  81333. }
  81334. else {
  81335. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  81336. }
  81337. }
  81338. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  81339. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  81340. };
  81341. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  81342. this._pointerDownOnMeshAsked = true;
  81343. if (this._currentMeshSelected && this._currentHit) {
  81344. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  81345. }
  81346. };
  81347. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  81348. if (this._currentMeshSelected && this._currentHit) {
  81349. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  81350. }
  81351. this._pointerDownOnMeshAsked = false;
  81352. };
  81353. VRExperienceHelperGazer.prototype._activatePointer = function () {
  81354. this._activePointer = true;
  81355. };
  81356. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  81357. this._activePointer = false;
  81358. };
  81359. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  81360. };
  81361. VRExperienceHelperGazer.prototype.dispose = function () {
  81362. this._interactionsEnabled = false;
  81363. this._teleportationEnabled = false;
  81364. };
  81365. VRExperienceHelperGazer._idCounter = 0;
  81366. return VRExperienceHelperGazer;
  81367. }());
  81368. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  81369. __extends(VRExperienceHelperControllerGazer, _super);
  81370. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  81371. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  81372. _this.webVRController = webVRController;
  81373. // Laser pointer
  81374. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  81375. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  81376. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81377. laserPointerMaterial.alpha = 0.6;
  81378. _this._laserPointer.material = laserPointerMaterial;
  81379. _this._laserPointer.rotation.x = Math.PI / 2;
  81380. _this._laserPointer.position.z = -0.5;
  81381. _this._laserPointer.isVisible = false;
  81382. if (!webVRController.mesh) {
  81383. // Create an empty mesh that is used prior to loading the high quality model
  81384. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  81385. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  81386. preloadPointerPose.rotation.x = -0.7;
  81387. preloadMesh.addChild(preloadPointerPose);
  81388. webVRController.attachToMesh(preloadMesh);
  81389. }
  81390. _this._setLaserPointerParent(webVRController.mesh);
  81391. return _this;
  81392. }
  81393. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  81394. return this.webVRController.getForwardRay(length);
  81395. };
  81396. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  81397. _super.prototype._activatePointer.call(this);
  81398. this._laserPointer.isVisible = true;
  81399. };
  81400. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  81401. _super.prototype._deactivatePointer.call(this);
  81402. this._laserPointer.isVisible = false;
  81403. };
  81404. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  81405. this._laserPointer.material.emissiveColor = color;
  81406. };
  81407. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  81408. var makeNotPick = function (root) {
  81409. root.name += " laserPointer";
  81410. root.getChildMeshes().forEach(function (c) {
  81411. makeNotPick(c);
  81412. });
  81413. };
  81414. makeNotPick(mesh);
  81415. var childMeshes = mesh.getChildMeshes();
  81416. this.webVRController._pointingPoseNode = null;
  81417. for (var i = 0; i < childMeshes.length; i++) {
  81418. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  81419. mesh = childMeshes[i];
  81420. this.webVRController._pointingPoseNode = mesh;
  81421. break;
  81422. }
  81423. }
  81424. this._laserPointer.parent = mesh;
  81425. };
  81426. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  81427. this._laserPointer.scaling.y = distance;
  81428. this._laserPointer.position.z = -distance / 2;
  81429. };
  81430. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  81431. _super.prototype.dispose.call(this);
  81432. this._laserPointer.dispose();
  81433. };
  81434. return VRExperienceHelperControllerGazer;
  81435. }(VRExperienceHelperGazer));
  81436. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  81437. __extends(VRExperienceHelperCameraGazer, _super);
  81438. function VRExperienceHelperCameraGazer(getCamera, scene) {
  81439. var _this = _super.call(this, scene) || this;
  81440. _this.getCamera = getCamera;
  81441. return _this;
  81442. }
  81443. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  81444. var camera = this.getCamera();
  81445. if (camera) {
  81446. return camera.getForwardRay(length);
  81447. }
  81448. else {
  81449. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  81450. }
  81451. };
  81452. return VRExperienceHelperCameraGazer;
  81453. }(VRExperienceHelperGazer));
  81454. /**
  81455. * Helps to quickly add VR support to an existing scene.
  81456. * See http://doc.babylonjs.com/how_to/webvr_helper
  81457. */
  81458. var VRExperienceHelper = /** @class */ (function () {
  81459. /**
  81460. * Instantiates a VRExperienceHelper.
  81461. * Helps to quickly add VR support to an existing scene.
  81462. * @param scene The scene the VRExperienceHelper belongs to.
  81463. * @param webVROptions Options to modify the vr experience helper's behavior.
  81464. */
  81465. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  81466. if (webVROptions === void 0) { webVROptions = {}; }
  81467. var _this = this;
  81468. this.webVROptions = webVROptions;
  81469. // Can the system support WebVR, even if a headset isn't plugged in?
  81470. this._webVRsupported = false;
  81471. // If WebVR is supported, is a headset plugged in and are we ready to present?
  81472. this._webVRready = false;
  81473. // Are we waiting for the requestPresent callback to complete?
  81474. this._webVRrequesting = false;
  81475. // Are we presenting to the headset right now?
  81476. this._webVRpresenting = false;
  81477. // Are we presenting in the fullscreen fallback?
  81478. this._fullscreenVRpresenting = false;
  81479. /**
  81480. * Observable raised when entering VR.
  81481. */
  81482. this.onEnteringVRObservable = new BABYLON.Observable();
  81483. /**
  81484. * Observable raised when exiting VR.
  81485. */
  81486. this.onExitingVRObservable = new BABYLON.Observable();
  81487. /**
  81488. * Observable raised when controller mesh is loaded.
  81489. */
  81490. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81491. this._useCustomVRButton = false;
  81492. this._teleportationRequested = false;
  81493. this._teleportActive = false;
  81494. this._floorMeshesCollection = [];
  81495. this._rotationAllowed = true;
  81496. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  81497. this._rotationRightAsked = false;
  81498. this._rotationLeftAsked = false;
  81499. this._isDefaultTeleportationTarget = true;
  81500. this._teleportationFillColor = "#444444";
  81501. this._teleportationBorderColor = "#FFFFFF";
  81502. this._rotationAngle = 0;
  81503. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  81504. this._padSensibilityUp = 0.65;
  81505. this._padSensibilityDown = 0.35;
  81506. this.leftController = null;
  81507. this.rightController = null;
  81508. /**
  81509. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  81510. */
  81511. this.onNewMeshSelected = new BABYLON.Observable();
  81512. /**
  81513. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  81514. */
  81515. this.onNewMeshPicked = new BABYLON.Observable();
  81516. /**
  81517. * Observable raised before camera teleportation
  81518. */
  81519. this.onBeforeCameraTeleport = new BABYLON.Observable();
  81520. /**
  81521. * Observable raised after camera teleportation
  81522. */
  81523. this.onAfterCameraTeleport = new BABYLON.Observable();
  81524. /**
  81525. * Observable raised when current selected mesh gets unselected
  81526. */
  81527. this.onSelectedMeshUnselected = new BABYLON.Observable();
  81528. /**
  81529. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  81530. */
  81531. this.teleportationEnabled = true;
  81532. this._teleportationInitialized = false;
  81533. this._interactionsEnabled = false;
  81534. this._interactionsRequested = false;
  81535. this._displayGaze = true;
  81536. this._displayLaserPointer = true;
  81537. this._onResize = function () {
  81538. _this.moveButtonToBottomRight();
  81539. if (_this._fullscreenVRpresenting && _this._webVRready) {
  81540. _this.exitVR();
  81541. }
  81542. };
  81543. this._onFullscreenChange = function () {
  81544. if (document.fullscreen !== undefined) {
  81545. _this._fullscreenVRpresenting = document.fullscreen;
  81546. }
  81547. else if (document.mozFullScreen !== undefined) {
  81548. _this._fullscreenVRpresenting = document.mozFullScreen;
  81549. }
  81550. else if (document.webkitIsFullScreen !== undefined) {
  81551. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  81552. }
  81553. else if (document.msIsFullScreen !== undefined) {
  81554. _this._fullscreenVRpresenting = document.msIsFullScreen;
  81555. }
  81556. if (!_this._fullscreenVRpresenting && _this._canvas) {
  81557. _this.exitVR();
  81558. if (!_this._useCustomVRButton) {
  81559. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  81560. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  81561. }
  81562. }
  81563. };
  81564. this.beforeRender = function () {
  81565. if (_this.leftController && _this.leftController._activePointer) {
  81566. _this._castRayAndSelectObject(_this.leftController);
  81567. }
  81568. if (_this.rightController && _this.rightController._activePointer) {
  81569. _this._castRayAndSelectObject(_this.rightController);
  81570. }
  81571. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  81572. _this._castRayAndSelectObject(_this._cameraGazer);
  81573. }
  81574. else {
  81575. _this._cameraGazer._gazeTracker.isVisible = false;
  81576. }
  81577. };
  81578. this._onNewGamepadConnected = function (gamepad) {
  81579. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81580. if (gamepad.leftStick) {
  81581. gamepad.onleftstickchanged(function (stickValues) {
  81582. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  81583. // Listening to classic/xbox gamepad only if no VR controller is active
  81584. if ((!_this.leftController && !_this.rightController) ||
  81585. ((_this.leftController && !_this.leftController._activePointer) &&
  81586. (_this.rightController && !_this.rightController._activePointer))) {
  81587. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  81588. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  81589. }
  81590. }
  81591. });
  81592. }
  81593. if (gamepad.rightStick) {
  81594. gamepad.onrightstickchanged(function (stickValues) {
  81595. if (_this._teleportationInitialized) {
  81596. _this._checkRotate(stickValues, _this._cameraGazer);
  81597. }
  81598. });
  81599. }
  81600. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  81601. gamepad.onbuttondown(function (buttonPressed) {
  81602. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81603. _this._cameraGazer._selectionPointerDown();
  81604. }
  81605. });
  81606. gamepad.onbuttonup(function (buttonPressed) {
  81607. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81608. _this._cameraGazer._selectionPointerUp();
  81609. }
  81610. });
  81611. }
  81612. }
  81613. else {
  81614. var webVRController = gamepad;
  81615. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  81616. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  81617. _this.rightController = controller;
  81618. }
  81619. else {
  81620. _this.leftController = controller;
  81621. }
  81622. _this._tryEnableInteractionOnController(controller);
  81623. }
  81624. };
  81625. // 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
  81626. this._tryEnableInteractionOnController = function (controller) {
  81627. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  81628. _this._enableInteractionOnController(controller);
  81629. }
  81630. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  81631. _this._enableTeleportationOnController(controller);
  81632. }
  81633. };
  81634. this._onNewGamepadDisconnected = function (gamepad) {
  81635. if (gamepad instanceof BABYLON.WebVRController) {
  81636. if (gamepad.hand === "left" && _this.leftController != null) {
  81637. _this.leftController.dispose();
  81638. _this.leftController = null;
  81639. }
  81640. if (gamepad.hand === "right" && _this.rightController != null) {
  81641. _this.rightController.dispose();
  81642. _this.rightController = null;
  81643. }
  81644. }
  81645. };
  81646. this._workingVector = BABYLON.Vector3.Zero();
  81647. this._workingQuaternion = BABYLON.Quaternion.Identity();
  81648. this._workingMatrix = BABYLON.Matrix.Identity();
  81649. this._scene = scene;
  81650. this._canvas = scene.getEngine().getRenderingCanvas();
  81651. // Parse options
  81652. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  81653. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  81654. }
  81655. if (webVROptions.createDeviceOrientationCamera === undefined) {
  81656. webVROptions.createDeviceOrientationCamera = true;
  81657. }
  81658. if (webVROptions.defaultHeight === undefined) {
  81659. webVROptions.defaultHeight = 1.7;
  81660. }
  81661. if (webVROptions.useCustomVRButton) {
  81662. this._useCustomVRButton = true;
  81663. if (webVROptions.customVRButton) {
  81664. this._btnVR = webVROptions.customVRButton;
  81665. }
  81666. }
  81667. if (webVROptions.rayLength) {
  81668. this._rayLength = webVROptions.rayLength;
  81669. }
  81670. this._defaultHeight = webVROptions.defaultHeight;
  81671. if (webVROptions.positionScale) {
  81672. this._rayLength *= webVROptions.positionScale;
  81673. this._defaultHeight *= webVROptions.positionScale;
  81674. }
  81675. // Set position
  81676. if (this._scene.activeCamera) {
  81677. this._position = this._scene.activeCamera.position.clone();
  81678. }
  81679. else {
  81680. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  81681. }
  81682. // Set non-vr camera
  81683. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  81684. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  81685. // Copy data from existing camera
  81686. if (this._scene.activeCamera) {
  81687. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  81688. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  81689. // Set rotation from previous camera
  81690. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  81691. var targetCamera = this._scene.activeCamera;
  81692. if (targetCamera.rotationQuaternion) {
  81693. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  81694. }
  81695. else {
  81696. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  81697. }
  81698. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  81699. }
  81700. }
  81701. this._scene.activeCamera = this._deviceOrientationCamera;
  81702. if (this._canvas) {
  81703. this._scene.activeCamera.attachControl(this._canvas);
  81704. }
  81705. }
  81706. else {
  81707. this._existingCamera = this._scene.activeCamera;
  81708. }
  81709. // Create VR cameras
  81710. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81711. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  81712. }
  81713. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  81714. this._webVRCamera.useStandingMatrix();
  81715. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  81716. // Create default button
  81717. if (!this._useCustomVRButton) {
  81718. this._btnVR = document.createElement("BUTTON");
  81719. this._btnVR.className = "babylonVRicon";
  81720. this._btnVR.id = "babylonVRiconbtn";
  81721. this._btnVR.title = "Click to switch to VR";
  81722. 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) }";
  81723. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  81724. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  81725. // css += ".babylonVRicon.vrdisplaysupported { }";
  81726. // css += ".babylonVRicon.vrdisplayready { }";
  81727. // css += ".babylonVRicon.vrdisplayrequesting { }";
  81728. var style = document.createElement('style');
  81729. style.appendChild(document.createTextNode(css));
  81730. document.getElementsByTagName('head')[0].appendChild(style);
  81731. this.moveButtonToBottomRight();
  81732. }
  81733. // VR button click event
  81734. if (this._btnVR) {
  81735. this._btnVR.addEventListener("click", function () {
  81736. if (!_this.isInVRMode) {
  81737. _this.enterVR();
  81738. }
  81739. else {
  81740. _this.exitVR();
  81741. }
  81742. });
  81743. }
  81744. // Window events
  81745. window.addEventListener("resize", this._onResize);
  81746. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  81747. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  81748. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  81749. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  81750. // Display vr button when headset is connected
  81751. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81752. this.displayVRButton();
  81753. }
  81754. else {
  81755. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  81756. if (e.vrDisplay) {
  81757. _this.displayVRButton();
  81758. }
  81759. });
  81760. }
  81761. // Exiting VR mode using 'ESC' key on desktop
  81762. this._onKeyDown = function (event) {
  81763. if (event.keyCode === 27 && _this.isInVRMode) {
  81764. _this.exitVR();
  81765. }
  81766. };
  81767. document.addEventListener("keydown", this._onKeyDown);
  81768. // Exiting VR mode double tapping the touch screen
  81769. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  81770. if (_this.isInVRMode) {
  81771. _this.exitVR();
  81772. if (_this._fullscreenVRpresenting) {
  81773. _this._scene.getEngine().switchFullscreen(true);
  81774. }
  81775. }
  81776. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  81777. // Listen for WebVR display changes
  81778. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  81779. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  81780. this._onVRRequestPresentStart = function () {
  81781. _this._webVRrequesting = true;
  81782. _this.updateButtonVisibility();
  81783. };
  81784. this._onVRRequestPresentComplete = function (success) {
  81785. _this._webVRrequesting = false;
  81786. _this.updateButtonVisibility();
  81787. };
  81788. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  81789. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  81790. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  81791. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81792. scene.onDisposeObservable.add(function () {
  81793. _this.dispose();
  81794. });
  81795. // Gamepad connection events
  81796. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  81797. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  81798. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  81799. this.updateButtonVisibility();
  81800. //create easing functions
  81801. this._circleEase = new BABYLON.CircleEase();
  81802. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81803. }
  81804. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  81805. /** Return this.onEnteringVRObservable
  81806. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  81807. */
  81808. get: function () {
  81809. return this.onEnteringVRObservable;
  81810. },
  81811. enumerable: true,
  81812. configurable: true
  81813. });
  81814. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  81815. /** Return this.onExitingVRObservable
  81816. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  81817. */
  81818. get: function () {
  81819. return this.onExitingVRObservable;
  81820. },
  81821. enumerable: true,
  81822. configurable: true
  81823. });
  81824. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  81825. /** Return this.onControllerMeshLoadedObservable
  81826. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  81827. */
  81828. get: function () {
  81829. return this.onControllerMeshLoadedObservable;
  81830. },
  81831. enumerable: true,
  81832. configurable: true
  81833. });
  81834. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  81835. /**
  81836. * The mesh used to display where the user is going to teleport.
  81837. */
  81838. get: function () {
  81839. return this._teleportationTarget;
  81840. },
  81841. /**
  81842. * Sets the mesh to be used to display where the user is going to teleport.
  81843. */
  81844. set: function (value) {
  81845. if (value) {
  81846. value.name = "teleportationTarget";
  81847. this._isDefaultTeleportationTarget = false;
  81848. this._teleportationTarget = value;
  81849. }
  81850. },
  81851. enumerable: true,
  81852. configurable: true
  81853. });
  81854. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  81855. /**
  81856. * The mesh used to display where the user is selecting,
  81857. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  81858. * See http://doc.babylonjs.com/resources/baking_transformations
  81859. */
  81860. get: function () {
  81861. return this._cameraGazer._gazeTracker;
  81862. },
  81863. set: function (value) {
  81864. if (value) {
  81865. this._cameraGazer._gazeTracker = value;
  81866. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  81867. this._cameraGazer._gazeTracker.isPickable = false;
  81868. this._cameraGazer._gazeTracker.isVisible = false;
  81869. this._cameraGazer._gazeTracker.name = "gazeTracker";
  81870. if (this.leftController) {
  81871. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81872. }
  81873. if (this.rightController) {
  81874. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81875. }
  81876. }
  81877. },
  81878. enumerable: true,
  81879. configurable: true
  81880. });
  81881. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  81882. /**
  81883. * If the ray of the gaze should be displayed.
  81884. */
  81885. get: function () {
  81886. return this._displayGaze;
  81887. },
  81888. /**
  81889. * Sets if the ray of the gaze should be displayed.
  81890. */
  81891. set: function (value) {
  81892. this._displayGaze = value;
  81893. if (!value) {
  81894. this._cameraGazer._gazeTracker.isVisible = false;
  81895. if (this.leftController) {
  81896. this.leftController._gazeTracker.isVisible = false;
  81897. }
  81898. if (this.rightController) {
  81899. this.rightController._gazeTracker.isVisible = false;
  81900. }
  81901. }
  81902. },
  81903. enumerable: true,
  81904. configurable: true
  81905. });
  81906. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  81907. /**
  81908. * If the ray of the LaserPointer should be displayed.
  81909. */
  81910. get: function () {
  81911. return this._displayLaserPointer;
  81912. },
  81913. /**
  81914. * Sets if the ray of the LaserPointer should be displayed.
  81915. */
  81916. set: function (value) {
  81917. this._displayLaserPointer = value;
  81918. if (!value) {
  81919. if (this.rightController) {
  81920. this.rightController._deactivatePointer();
  81921. this.rightController._gazeTracker.isVisible = false;
  81922. }
  81923. if (this.leftController) {
  81924. this.leftController._deactivatePointer();
  81925. this.leftController._gazeTracker.isVisible = false;
  81926. }
  81927. }
  81928. else {
  81929. if (this.rightController) {
  81930. this.rightController._activatePointer();
  81931. }
  81932. else if (this.leftController) {
  81933. this.leftController._activatePointer();
  81934. }
  81935. }
  81936. },
  81937. enumerable: true,
  81938. configurable: true
  81939. });
  81940. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  81941. /**
  81942. * The deviceOrientationCamera used as the camera when not in VR.
  81943. */
  81944. get: function () {
  81945. return this._deviceOrientationCamera;
  81946. },
  81947. enumerable: true,
  81948. configurable: true
  81949. });
  81950. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  81951. /**
  81952. * Based on the current WebVR support, returns the current VR camera used.
  81953. */
  81954. get: function () {
  81955. if (this._webVRready) {
  81956. return this._webVRCamera;
  81957. }
  81958. else {
  81959. return this._scene.activeCamera;
  81960. }
  81961. },
  81962. enumerable: true,
  81963. configurable: true
  81964. });
  81965. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  81966. /**
  81967. * The webVRCamera which is used when in VR.
  81968. */
  81969. get: function () {
  81970. return this._webVRCamera;
  81971. },
  81972. enumerable: true,
  81973. configurable: true
  81974. });
  81975. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  81976. /**
  81977. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  81978. */
  81979. get: function () {
  81980. return this._vrDeviceOrientationCamera;
  81981. },
  81982. enumerable: true,
  81983. configurable: true
  81984. });
  81985. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  81986. get: function () {
  81987. var result = this._cameraGazer._teleportationRequestInitiated
  81988. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  81989. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  81990. return result;
  81991. },
  81992. enumerable: true,
  81993. configurable: true
  81994. });
  81995. // Raised when one of the controller has loaded successfully its associated default mesh
  81996. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  81997. if (this.leftController && this.leftController.webVRController == webVRController) {
  81998. if (webVRController.mesh) {
  81999. this.leftController._setLaserPointerParent(webVRController.mesh);
  82000. }
  82001. }
  82002. if (this.rightController && this.rightController.webVRController == webVRController) {
  82003. if (webVRController.mesh) {
  82004. this.rightController._setLaserPointerParent(webVRController.mesh);
  82005. }
  82006. }
  82007. try {
  82008. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  82009. }
  82010. catch (err) {
  82011. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  82012. }
  82013. };
  82014. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  82015. /**
  82016. * Gets a value indicating if we are currently in VR mode.
  82017. */
  82018. get: function () {
  82019. return this._webVRpresenting || this._fullscreenVRpresenting;
  82020. },
  82021. enumerable: true,
  82022. configurable: true
  82023. });
  82024. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  82025. var vrDisplay = this._scene.getEngine().getVRDevice();
  82026. if (vrDisplay) {
  82027. var wasPresenting = this._webVRpresenting;
  82028. // A VR display is connected
  82029. this._webVRpresenting = vrDisplay.isPresenting;
  82030. if (wasPresenting && !this._webVRpresenting)
  82031. this.exitVR();
  82032. }
  82033. else {
  82034. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  82035. }
  82036. this.updateButtonVisibility();
  82037. };
  82038. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  82039. this._webVRsupported = eventArgs.vrSupported;
  82040. this._webVRready = !!eventArgs.vrDisplay;
  82041. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  82042. this.updateButtonVisibility();
  82043. };
  82044. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  82045. if (this._canvas && !this._useCustomVRButton) {
  82046. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  82047. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  82048. }
  82049. };
  82050. VRExperienceHelper.prototype.displayVRButton = function () {
  82051. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  82052. document.body.appendChild(this._btnVR);
  82053. this._btnVRDisplayed = true;
  82054. }
  82055. };
  82056. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  82057. if (!this._btnVR || this._useCustomVRButton) {
  82058. return;
  82059. }
  82060. this._btnVR.className = "babylonVRicon";
  82061. if (this.isInVRMode) {
  82062. this._btnVR.className += " vrdisplaypresenting";
  82063. }
  82064. else {
  82065. if (this._webVRready)
  82066. this._btnVR.className += " vrdisplayready";
  82067. if (this._webVRsupported)
  82068. this._btnVR.className += " vrdisplaysupported";
  82069. if (this._webVRrequesting)
  82070. this._btnVR.className += " vrdisplayrequesting";
  82071. }
  82072. };
  82073. /**
  82074. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  82075. * Otherwise, will use the fullscreen API.
  82076. */
  82077. VRExperienceHelper.prototype.enterVR = function () {
  82078. if (this.onEnteringVRObservable) {
  82079. try {
  82080. this.onEnteringVRObservable.notifyObservers(this);
  82081. }
  82082. catch (err) {
  82083. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  82084. }
  82085. }
  82086. if (this._scene.activeCamera) {
  82087. this._position = this._scene.activeCamera.position.clone();
  82088. // make sure that we return to the last active camera
  82089. this._existingCamera = this._scene.activeCamera;
  82090. }
  82091. if (this._webVRrequesting)
  82092. return;
  82093. // If WebVR is supported and a headset is connected
  82094. if (this._webVRready) {
  82095. if (!this._webVRpresenting) {
  82096. this._webVRCamera.position = this._position;
  82097. this._scene.activeCamera = this._webVRCamera;
  82098. }
  82099. }
  82100. else if (this._vrDeviceOrientationCamera) {
  82101. this._vrDeviceOrientationCamera.position = this._position;
  82102. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  82103. this._scene.getEngine().switchFullscreen(true);
  82104. this.updateButtonVisibility();
  82105. }
  82106. if (this._scene.activeCamera && this._canvas) {
  82107. this._scene.activeCamera.attachControl(this._canvas);
  82108. }
  82109. if (this._interactionsEnabled) {
  82110. this._scene.registerBeforeRender(this.beforeRender);
  82111. }
  82112. };
  82113. /**
  82114. * Attempt to exit VR, or fullscreen.
  82115. */
  82116. VRExperienceHelper.prototype.exitVR = function () {
  82117. if (this.onExitingVRObservable) {
  82118. try {
  82119. this.onExitingVRObservable.notifyObservers(this);
  82120. }
  82121. catch (err) {
  82122. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  82123. }
  82124. }
  82125. if (this._webVRpresenting) {
  82126. this._scene.getEngine().disableVR();
  82127. }
  82128. if (this._scene.activeCamera) {
  82129. this._position = this._scene.activeCamera.position.clone();
  82130. }
  82131. if (this._deviceOrientationCamera) {
  82132. this._deviceOrientationCamera.position = this._position;
  82133. this._scene.activeCamera = this._deviceOrientationCamera;
  82134. if (this._canvas) {
  82135. this._scene.activeCamera.attachControl(this._canvas);
  82136. }
  82137. }
  82138. else if (this._existingCamera) {
  82139. this._existingCamera.position = this._position;
  82140. this._scene.activeCamera = this._existingCamera;
  82141. }
  82142. this.updateButtonVisibility();
  82143. if (this._interactionsEnabled) {
  82144. this._scene.unregisterBeforeRender(this.beforeRender);
  82145. }
  82146. };
  82147. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  82148. /**
  82149. * The position of the vr experience helper.
  82150. */
  82151. get: function () {
  82152. return this._position;
  82153. },
  82154. /**
  82155. * Sets the position of the vr experience helper.
  82156. */
  82157. set: function (value) {
  82158. this._position = value;
  82159. if (this._scene.activeCamera) {
  82160. this._scene.activeCamera.position = value;
  82161. }
  82162. },
  82163. enumerable: true,
  82164. configurable: true
  82165. });
  82166. /**
  82167. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  82168. */
  82169. VRExperienceHelper.prototype.enableInteractions = function () {
  82170. var _this = this;
  82171. if (!this._interactionsEnabled) {
  82172. this._interactionsRequested = true;
  82173. if (this.leftController) {
  82174. this._enableInteractionOnController(this.leftController);
  82175. }
  82176. if (this.rightController) {
  82177. this._enableInteractionOnController(this.rightController);
  82178. }
  82179. this.raySelectionPredicate = function (mesh) {
  82180. return mesh.isVisible;
  82181. };
  82182. this.meshSelectionPredicate = function (mesh) {
  82183. return true;
  82184. };
  82185. this._raySelectionPredicate = function (mesh) {
  82186. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  82187. && mesh.name.indexOf("teleportationTarget") === -1
  82188. && mesh.name.indexOf("torusTeleportation") === -1
  82189. && mesh.name.indexOf("laserPointer") === -1)) {
  82190. return _this.raySelectionPredicate(mesh);
  82191. }
  82192. return false;
  82193. };
  82194. this._interactionsEnabled = true;
  82195. }
  82196. };
  82197. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  82198. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  82199. if (this._floorMeshesCollection[i].id === mesh.id) {
  82200. return true;
  82201. }
  82202. }
  82203. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  82204. return true;
  82205. }
  82206. return false;
  82207. };
  82208. /**
  82209. * Adds a floor mesh to be used for teleportation.
  82210. * @param floorMesh the mesh to be used for teleportation.
  82211. */
  82212. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  82213. if (!this._floorMeshesCollection) {
  82214. return;
  82215. }
  82216. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  82217. return;
  82218. }
  82219. this._floorMeshesCollection.push(floorMesh);
  82220. };
  82221. /**
  82222. * Removes a floor mesh from being used for teleportation.
  82223. * @param floorMesh the mesh to be removed.
  82224. */
  82225. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  82226. if (!this._floorMeshesCollection) {
  82227. return;
  82228. }
  82229. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  82230. if (meshIndex !== -1) {
  82231. this._floorMeshesCollection.splice(meshIndex, 1);
  82232. }
  82233. };
  82234. /**
  82235. * Enables interactions and teleportation using the VR controllers and gaze.
  82236. * @param vrTeleportationOptions options to modify teleportation behavior.
  82237. */
  82238. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  82239. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  82240. if (!this._teleportationInitialized) {
  82241. this._teleportationRequested = true;
  82242. this.enableInteractions();
  82243. if (vrTeleportationOptions.floorMeshName) {
  82244. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  82245. }
  82246. if (vrTeleportationOptions.floorMeshes) {
  82247. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  82248. }
  82249. if (this.leftController != null) {
  82250. this._enableTeleportationOnController(this.leftController);
  82251. }
  82252. if (this.rightController != null) {
  82253. this._enableTeleportationOnController(this.rightController);
  82254. }
  82255. // Creates an image processing post process for the vignette not relying
  82256. // on the main scene configuration for image processing to reduce setup and spaces
  82257. // (gamma/linear) conflicts.
  82258. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  82259. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82260. imageProcessingConfiguration.vignetteEnabled = true;
  82261. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  82262. this._webVRCamera.detachPostProcess(this._postProcessMove);
  82263. this._teleportationInitialized = true;
  82264. if (this._isDefaultTeleportationTarget) {
  82265. this._createTeleportationCircles();
  82266. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  82267. }
  82268. }
  82269. };
  82270. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  82271. var _this = this;
  82272. var controllerMesh = controller.webVRController.mesh;
  82273. if (controllerMesh) {
  82274. controller._interactionsEnabled = true;
  82275. controller._activatePointer();
  82276. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  82277. // Enabling / disabling laserPointer
  82278. if (_this._displayLaserPointer && stateObject.value === 1) {
  82279. if (controller._activePointer) {
  82280. controller._deactivatePointer();
  82281. }
  82282. else {
  82283. controller._activatePointer();
  82284. }
  82285. if (_this.displayGaze) {
  82286. controller._gazeTracker.isVisible = controller._activePointer;
  82287. }
  82288. }
  82289. });
  82290. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  82291. if (!controller._pointerDownOnMeshAsked) {
  82292. if (stateObject.value > _this._padSensibilityUp) {
  82293. controller._selectionPointerDown();
  82294. }
  82295. }
  82296. else if (stateObject.value < _this._padSensibilityDown) {
  82297. controller._selectionPointerUp();
  82298. }
  82299. });
  82300. }
  82301. };
  82302. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  82303. // Dont teleport if another gaze already requested teleportation
  82304. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  82305. return;
  82306. }
  82307. if (!gazer._teleportationRequestInitiated) {
  82308. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  82309. gazer._activatePointer();
  82310. gazer._teleportationRequestInitiated = true;
  82311. }
  82312. }
  82313. else {
  82314. // Listening to the proper controller values changes to confirm teleportation
  82315. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  82316. if (this._teleportActive) {
  82317. this._teleportCamera(this._haloCenter);
  82318. }
  82319. gazer._teleportationRequestInitiated = false;
  82320. }
  82321. }
  82322. };
  82323. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  82324. // Only rotate when user is not currently selecting a teleportation location
  82325. if (gazer._teleportationRequestInitiated) {
  82326. return;
  82327. }
  82328. if (!this._rotationLeftAsked) {
  82329. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  82330. this._rotationLeftAsked = true;
  82331. if (this._rotationAllowed) {
  82332. this._rotateCamera(false);
  82333. }
  82334. }
  82335. }
  82336. else {
  82337. if (stateObject.x > -this._padSensibilityDown) {
  82338. this._rotationLeftAsked = false;
  82339. }
  82340. }
  82341. if (!this._rotationRightAsked) {
  82342. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  82343. this._rotationRightAsked = true;
  82344. if (this._rotationAllowed) {
  82345. this._rotateCamera(true);
  82346. }
  82347. }
  82348. }
  82349. else {
  82350. if (stateObject.x < this._padSensibilityDown) {
  82351. this._rotationRightAsked = false;
  82352. }
  82353. }
  82354. };
  82355. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  82356. // Only teleport backwards when user is not currently selecting a teleportation location
  82357. if (gazer._teleportationRequestInitiated) {
  82358. return;
  82359. }
  82360. // Teleport backwards
  82361. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  82362. if (!gazer._teleportationBackRequestInitiated) {
  82363. if (!this.currentVRCamera) {
  82364. return;
  82365. }
  82366. // Get rotation and position of the current camera
  82367. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  82368. var position = this.currentVRCamera.position;
  82369. // If the camera has device position, use that instead
  82370. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  82371. rotation = this.currentVRCamera.deviceRotationQuaternion;
  82372. position = this.currentVRCamera.devicePosition;
  82373. }
  82374. // Get matrix with only the y rotation of the device rotation
  82375. rotation.toEulerAnglesToRef(this._workingVector);
  82376. this._workingVector.z = 0;
  82377. this._workingVector.x = 0;
  82378. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  82379. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  82380. // Rotate backwards ray by device rotation to cast at the ground behind the user
  82381. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  82382. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  82383. var ray = new BABYLON.Ray(position, this._workingVector);
  82384. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  82385. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  82386. this._teleportCamera(hit.pickedPoint);
  82387. }
  82388. gazer._teleportationBackRequestInitiated = true;
  82389. }
  82390. }
  82391. else {
  82392. gazer._teleportationBackRequestInitiated = false;
  82393. }
  82394. };
  82395. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  82396. var _this = this;
  82397. var controllerMesh = controller.webVRController.mesh;
  82398. if (controllerMesh) {
  82399. if (!controller._interactionsEnabled) {
  82400. this._enableInteractionOnController(controller);
  82401. }
  82402. controller._interactionsEnabled = true;
  82403. controller._teleportationEnabled = true;
  82404. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82405. controller._dpadPressed = false;
  82406. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  82407. controller._dpadPressed = stateObject.pressed;
  82408. if (!controller._dpadPressed) {
  82409. _this._rotationLeftAsked = false;
  82410. _this._rotationRightAsked = false;
  82411. controller._teleportationBackRequestInitiated = false;
  82412. }
  82413. });
  82414. }
  82415. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  82416. if (_this.teleportationEnabled) {
  82417. _this._checkTeleportBackwards(stateObject, controller);
  82418. _this._checkTeleportWithRay(stateObject, controller);
  82419. }
  82420. _this._checkRotate(stateObject, controller);
  82421. });
  82422. }
  82423. };
  82424. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  82425. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  82426. this._teleportationTarget.isPickable = false;
  82427. var length = 512;
  82428. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  82429. dynamicTexture.hasAlpha = true;
  82430. var context = dynamicTexture.getContext();
  82431. var centerX = length / 2;
  82432. var centerY = length / 2;
  82433. var radius = 200;
  82434. context.beginPath();
  82435. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  82436. context.fillStyle = this._teleportationFillColor;
  82437. context.fill();
  82438. context.lineWidth = 10;
  82439. context.strokeStyle = this._teleportationBorderColor;
  82440. context.stroke();
  82441. context.closePath();
  82442. dynamicTexture.update();
  82443. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  82444. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  82445. this._teleportationTarget.material = teleportationCircleMaterial;
  82446. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  82447. torus.isPickable = false;
  82448. torus.parent = this._teleportationTarget;
  82449. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82450. var keys = [];
  82451. keys.push({
  82452. frame: 0,
  82453. value: 0
  82454. });
  82455. keys.push({
  82456. frame: 30,
  82457. value: 0.4
  82458. });
  82459. keys.push({
  82460. frame: 60,
  82461. value: 0
  82462. });
  82463. animationInnerCircle.setKeys(keys);
  82464. var easingFunction = new BABYLON.SineEase();
  82465. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82466. animationInnerCircle.setEasingFunction(easingFunction);
  82467. torus.animations = [];
  82468. torus.animations.push(animationInnerCircle);
  82469. this._scene.beginAnimation(torus, 0, 60, true);
  82470. this._hideTeleportationTarget();
  82471. };
  82472. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  82473. this._teleportActive = true;
  82474. if (this._teleportationInitialized) {
  82475. this._teleportationTarget.isVisible = true;
  82476. if (this._isDefaultTeleportationTarget) {
  82477. this._teleportationTarget.getChildren()[0].isVisible = true;
  82478. }
  82479. }
  82480. };
  82481. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  82482. this._teleportActive = false;
  82483. if (this._teleportationInitialized) {
  82484. this._teleportationTarget.isVisible = false;
  82485. if (this._isDefaultTeleportationTarget) {
  82486. this._teleportationTarget.getChildren()[0].isVisible = false;
  82487. }
  82488. }
  82489. };
  82490. VRExperienceHelper.prototype._rotateCamera = function (right) {
  82491. var _this = this;
  82492. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82493. return;
  82494. }
  82495. if (right) {
  82496. this._rotationAngle++;
  82497. }
  82498. else {
  82499. this._rotationAngle--;
  82500. }
  82501. this.currentVRCamera.animations = [];
  82502. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  82503. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82504. var animationRotationKeys = [];
  82505. animationRotationKeys.push({
  82506. frame: 0,
  82507. value: this.currentVRCamera.rotationQuaternion
  82508. });
  82509. animationRotationKeys.push({
  82510. frame: 6,
  82511. value: target
  82512. });
  82513. animationRotation.setKeys(animationRotationKeys);
  82514. animationRotation.setEasingFunction(this._circleEase);
  82515. this.currentVRCamera.animations.push(animationRotation);
  82516. this._postProcessMove.animations = [];
  82517. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82518. var vignetteWeightKeys = [];
  82519. vignetteWeightKeys.push({
  82520. frame: 0,
  82521. value: 0
  82522. });
  82523. vignetteWeightKeys.push({
  82524. frame: 3,
  82525. value: 4
  82526. });
  82527. vignetteWeightKeys.push({
  82528. frame: 6,
  82529. value: 0
  82530. });
  82531. animationPP.setKeys(vignetteWeightKeys);
  82532. animationPP.setEasingFunction(this._circleEase);
  82533. this._postProcessMove.animations.push(animationPP);
  82534. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82535. var vignetteStretchKeys = [];
  82536. vignetteStretchKeys.push({
  82537. frame: 0,
  82538. value: 0
  82539. });
  82540. vignetteStretchKeys.push({
  82541. frame: 3,
  82542. value: 10
  82543. });
  82544. vignetteStretchKeys.push({
  82545. frame: 6,
  82546. value: 0
  82547. });
  82548. animationPP2.setKeys(vignetteStretchKeys);
  82549. animationPP2.setEasingFunction(this._circleEase);
  82550. this._postProcessMove.animations.push(animationPP2);
  82551. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82552. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82553. this._postProcessMove.samples = 4;
  82554. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82555. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  82556. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82557. });
  82558. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  82559. };
  82560. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  82561. if (hit.pickedPoint) {
  82562. if (gazer._teleportationRequestInitiated) {
  82563. this._displayTeleportationTarget();
  82564. this._haloCenter.copyFrom(hit.pickedPoint);
  82565. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  82566. }
  82567. var pickNormal = hit.getNormal(true, false);
  82568. if (pickNormal) {
  82569. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82570. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82571. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  82572. }
  82573. this._teleportationTarget.position.y += 0.1;
  82574. }
  82575. };
  82576. VRExperienceHelper.prototype._teleportCamera = function (location) {
  82577. var _this = this;
  82578. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82579. return;
  82580. }
  82581. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  82582. // offset of the headset from the anchor.
  82583. if (this.webVRCamera.leftCamera) {
  82584. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  82585. this._workingVector.subtractInPlace(this.webVRCamera.position);
  82586. location.subtractToRef(this._workingVector, this._workingVector);
  82587. }
  82588. else {
  82589. this._workingVector.copyFrom(location);
  82590. }
  82591. // Add height to account for user's height offset
  82592. if (this.isInVRMode) {
  82593. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  82594. }
  82595. else {
  82596. this._workingVector.y += this._defaultHeight;
  82597. }
  82598. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  82599. // Create animation from the camera's position to the new location
  82600. this.currentVRCamera.animations = [];
  82601. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82602. var animationCameraTeleportationKeys = [{
  82603. frame: 0,
  82604. value: this.currentVRCamera.position
  82605. },
  82606. {
  82607. frame: 11,
  82608. value: this._workingVector
  82609. }
  82610. ];
  82611. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  82612. animationCameraTeleportation.setEasingFunction(this._circleEase);
  82613. this.currentVRCamera.animations.push(animationCameraTeleportation);
  82614. this._postProcessMove.animations = [];
  82615. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82616. var vignetteWeightKeys = [];
  82617. vignetteWeightKeys.push({
  82618. frame: 0,
  82619. value: 0
  82620. });
  82621. vignetteWeightKeys.push({
  82622. frame: 5,
  82623. value: 8
  82624. });
  82625. vignetteWeightKeys.push({
  82626. frame: 11,
  82627. value: 0
  82628. });
  82629. animationPP.setKeys(vignetteWeightKeys);
  82630. this._postProcessMove.animations.push(animationPP);
  82631. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82632. var vignetteStretchKeys = [];
  82633. vignetteStretchKeys.push({
  82634. frame: 0,
  82635. value: 0
  82636. });
  82637. vignetteStretchKeys.push({
  82638. frame: 5,
  82639. value: 10
  82640. });
  82641. vignetteStretchKeys.push({
  82642. frame: 11,
  82643. value: 0
  82644. });
  82645. animationPP2.setKeys(vignetteStretchKeys);
  82646. this._postProcessMove.animations.push(animationPP2);
  82647. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82648. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82649. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82650. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  82651. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82652. });
  82653. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  82654. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  82655. });
  82656. this._hideTeleportationTarget();
  82657. };
  82658. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  82659. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82660. return;
  82661. }
  82662. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  82663. // Moving the gazeTracker on the mesh face targetted
  82664. if (hit && hit.pickedPoint) {
  82665. if (this._displayGaze) {
  82666. var multiplier = 1;
  82667. gazer._gazeTracker.isVisible = true;
  82668. if (gazer._isActionableMesh) {
  82669. multiplier = 3;
  82670. }
  82671. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  82672. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  82673. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  82674. var pickNormal = hit.getNormal();
  82675. // To avoid z-fighting
  82676. var deltaFighting = 0.002;
  82677. if (pickNormal) {
  82678. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82679. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82680. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  82681. }
  82682. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  82683. if (gazer._gazeTracker.position.x < 0) {
  82684. gazer._gazeTracker.position.x += deltaFighting;
  82685. }
  82686. else {
  82687. gazer._gazeTracker.position.x -= deltaFighting;
  82688. }
  82689. if (gazer._gazeTracker.position.y < 0) {
  82690. gazer._gazeTracker.position.y += deltaFighting;
  82691. }
  82692. else {
  82693. gazer._gazeTracker.position.y -= deltaFighting;
  82694. }
  82695. if (gazer._gazeTracker.position.z < 0) {
  82696. gazer._gazeTracker.position.z += deltaFighting;
  82697. }
  82698. else {
  82699. gazer._gazeTracker.position.z -= deltaFighting;
  82700. }
  82701. }
  82702. // Changing the size of the laser pointer based on the distance from the targetted point
  82703. gazer._updatePointerDistance(hit.distance);
  82704. }
  82705. else {
  82706. gazer._gazeTracker.isVisible = false;
  82707. }
  82708. if (hit && hit.pickedMesh) {
  82709. gazer._currentHit = hit;
  82710. if (gazer._pointerDownOnMeshAsked) {
  82711. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  82712. }
  82713. // The object selected is the floor, we're in a teleportation scenario
  82714. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  82715. // Moving the teleportation area to this targetted point
  82716. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  82717. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  82718. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82719. }
  82720. gazer._currentMeshSelected = null;
  82721. if (gazer._teleportationRequestInitiated) {
  82722. this._moveTeleportationSelectorTo(hit, gazer);
  82723. }
  82724. return;
  82725. }
  82726. // If not, we're in a selection scenario
  82727. //this._teleportationAllowed = false;
  82728. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  82729. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  82730. this.onNewMeshPicked.notifyObservers(hit);
  82731. gazer._currentMeshSelected = hit.pickedMesh;
  82732. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  82733. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  82734. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  82735. gazer._isActionableMesh = true;
  82736. }
  82737. else {
  82738. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82739. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82740. gazer._isActionableMesh = false;
  82741. }
  82742. try {
  82743. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  82744. }
  82745. catch (err) {
  82746. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  82747. }
  82748. }
  82749. else {
  82750. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82751. gazer._currentMeshSelected = null;
  82752. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82753. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82754. }
  82755. }
  82756. }
  82757. else {
  82758. gazer._currentHit = null;
  82759. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82760. gazer._currentMeshSelected = null;
  82761. //this._teleportationAllowed = false;
  82762. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82763. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82764. }
  82765. };
  82766. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  82767. if (mesh) {
  82768. this.onSelectedMeshUnselected.notifyObservers(mesh);
  82769. }
  82770. };
  82771. /**
  82772. * Sets the color of the laser ray from the vr controllers.
  82773. * @param color new color for the ray.
  82774. */
  82775. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  82776. if (this.leftController) {
  82777. this.leftController._setLaserPointerColor(color);
  82778. }
  82779. if (this.rightController) {
  82780. this.rightController._setLaserPointerColor(color);
  82781. }
  82782. };
  82783. /**
  82784. * Sets the color of the ray from the vr headsets gaze.
  82785. * @param color new color for the ray.
  82786. */
  82787. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  82788. if (!this._cameraGazer._gazeTracker.material) {
  82789. return;
  82790. }
  82791. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  82792. if (this.leftController) {
  82793. this.leftController._gazeTracker.material.emissiveColor = color;
  82794. }
  82795. if (this.rightController) {
  82796. this.rightController._gazeTracker.material.emissiveColor = color;
  82797. }
  82798. };
  82799. /**
  82800. * Exits VR and disposes of the vr experience helper
  82801. */
  82802. VRExperienceHelper.prototype.dispose = function () {
  82803. if (this.isInVRMode) {
  82804. this.exitVR();
  82805. }
  82806. if (this._postProcessMove) {
  82807. this._postProcessMove.dispose();
  82808. }
  82809. if (this._webVRCamera) {
  82810. this._webVRCamera.dispose();
  82811. }
  82812. if (this._vrDeviceOrientationCamera) {
  82813. this._vrDeviceOrientationCamera.dispose();
  82814. }
  82815. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  82816. document.body.removeChild(this._btnVR);
  82817. }
  82818. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  82819. this._deviceOrientationCamera.dispose();
  82820. }
  82821. if (this._cameraGazer) {
  82822. this._cameraGazer.dispose();
  82823. }
  82824. if (this.leftController) {
  82825. this.leftController.dispose();
  82826. }
  82827. if (this.rightController) {
  82828. this.rightController.dispose();
  82829. }
  82830. if (this._teleportationTarget) {
  82831. this._teleportationTarget.dispose();
  82832. }
  82833. this._floorMeshesCollection = [];
  82834. document.removeEventListener("keydown", this._onKeyDown);
  82835. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82836. window.removeEventListener("resize", this._onResize);
  82837. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  82838. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  82839. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  82840. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  82841. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  82842. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  82843. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  82844. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82845. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  82846. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  82847. this._scene.unregisterBeforeRender(this.beforeRender);
  82848. };
  82849. /**
  82850. * Gets the name of the VRExperienceHelper class
  82851. * @returns "VRExperienceHelper"
  82852. */
  82853. VRExperienceHelper.prototype.getClassName = function () {
  82854. return "VRExperienceHelper";
  82855. };
  82856. return VRExperienceHelper;
  82857. }());
  82858. BABYLON.VRExperienceHelper = VRExperienceHelper;
  82859. })(BABYLON || (BABYLON = {}));
  82860. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  82861. // Mainly based on these 2 articles :
  82862. // 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
  82863. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  82864. var BABYLON;
  82865. (function (BABYLON) {
  82866. var JoystickAxis;
  82867. (function (JoystickAxis) {
  82868. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  82869. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  82870. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  82871. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  82872. var VirtualJoystick = /** @class */ (function () {
  82873. function VirtualJoystick(leftJoystick) {
  82874. var _this = this;
  82875. if (leftJoystick) {
  82876. this._leftJoystick = true;
  82877. }
  82878. else {
  82879. this._leftJoystick = false;
  82880. }
  82881. VirtualJoystick._globalJoystickIndex++;
  82882. // By default left & right arrow keys are moving the X
  82883. // and up & down keys are moving the Y
  82884. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82885. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82886. this.reverseLeftRight = false;
  82887. this.reverseUpDown = false;
  82888. // collections of pointers
  82889. this._touches = new BABYLON.StringDictionary();
  82890. this.deltaPosition = BABYLON.Vector3.Zero();
  82891. this._joystickSensibility = 25;
  82892. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82893. this._onResize = function (evt) {
  82894. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82895. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82896. if (VirtualJoystick.vjCanvas) {
  82897. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  82898. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  82899. }
  82900. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  82901. };
  82902. // injecting a canvas element on top of the canvas 3D game
  82903. if (!VirtualJoystick.vjCanvas) {
  82904. window.addEventListener("resize", this._onResize, false);
  82905. VirtualJoystick.vjCanvas = document.createElement("canvas");
  82906. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82907. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82908. VirtualJoystick.vjCanvas.width = window.innerWidth;
  82909. VirtualJoystick.vjCanvas.height = window.innerHeight;
  82910. VirtualJoystick.vjCanvas.style.width = "100%";
  82911. VirtualJoystick.vjCanvas.style.height = "100%";
  82912. VirtualJoystick.vjCanvas.style.position = "absolute";
  82913. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  82914. VirtualJoystick.vjCanvas.style.top = "0px";
  82915. VirtualJoystick.vjCanvas.style.left = "0px";
  82916. VirtualJoystick.vjCanvas.style.zIndex = "5";
  82917. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  82918. // Support for jQuery PEP polyfill
  82919. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  82920. var context = VirtualJoystick.vjCanvas.getContext('2d');
  82921. if (!context) {
  82922. throw new Error("Unable to create canvas for virtual joystick");
  82923. }
  82924. VirtualJoystick.vjCanvasContext = context;
  82925. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  82926. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82927. document.body.appendChild(VirtualJoystick.vjCanvas);
  82928. }
  82929. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  82930. this.pressed = false;
  82931. // default joystick color
  82932. this._joystickColor = "cyan";
  82933. this._joystickPointerID = -1;
  82934. // current joystick position
  82935. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  82936. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  82937. // origin joystick position
  82938. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  82939. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  82940. this._onPointerDownHandlerRef = function (evt) {
  82941. _this._onPointerDown(evt);
  82942. };
  82943. this._onPointerMoveHandlerRef = function (evt) {
  82944. _this._onPointerMove(evt);
  82945. };
  82946. this._onPointerUpHandlerRef = function (evt) {
  82947. _this._onPointerUp(evt);
  82948. };
  82949. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  82950. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  82951. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  82952. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  82953. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  82954. evt.preventDefault(); // Disables system menu
  82955. }, false);
  82956. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82957. }
  82958. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  82959. this._joystickSensibility = newJoystickSensibility;
  82960. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82961. };
  82962. VirtualJoystick.prototype._onPointerDown = function (e) {
  82963. var positionOnScreenCondition;
  82964. e.preventDefault();
  82965. if (this._leftJoystick === true) {
  82966. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  82967. }
  82968. else {
  82969. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  82970. }
  82971. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  82972. // First contact will be dedicated to the virtual joystick
  82973. this._joystickPointerID = e.pointerId;
  82974. this._joystickPointerStartPos.x = e.clientX;
  82975. this._joystickPointerStartPos.y = e.clientY;
  82976. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  82977. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  82978. this._deltaJoystickVector.x = 0;
  82979. this._deltaJoystickVector.y = 0;
  82980. this.pressed = true;
  82981. this._touches.add(e.pointerId.toString(), e);
  82982. }
  82983. else {
  82984. // You can only trigger the action buttons with a joystick declared
  82985. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  82986. this._action();
  82987. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  82988. }
  82989. }
  82990. };
  82991. VirtualJoystick.prototype._onPointerMove = function (e) {
  82992. // If the current pointer is the one associated to the joystick (first touch contact)
  82993. if (this._joystickPointerID == e.pointerId) {
  82994. this._joystickPointerPos.x = e.clientX;
  82995. this._joystickPointerPos.y = e.clientY;
  82996. this._deltaJoystickVector = this._joystickPointerPos.clone();
  82997. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  82998. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  82999. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  83000. switch (this._axisTargetedByLeftAndRight) {
  83001. case JoystickAxis.X:
  83002. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  83003. break;
  83004. case JoystickAxis.Y:
  83005. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  83006. break;
  83007. case JoystickAxis.Z:
  83008. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  83009. break;
  83010. }
  83011. var directionUpDown = this.reverseUpDown ? 1 : -1;
  83012. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  83013. switch (this._axisTargetedByUpAndDown) {
  83014. case JoystickAxis.X:
  83015. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  83016. break;
  83017. case JoystickAxis.Y:
  83018. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  83019. break;
  83020. case JoystickAxis.Z:
  83021. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  83022. break;
  83023. }
  83024. }
  83025. else {
  83026. var data = this._touches.get(e.pointerId.toString());
  83027. if (data) {
  83028. data.x = e.clientX;
  83029. data.y = e.clientY;
  83030. }
  83031. }
  83032. };
  83033. VirtualJoystick.prototype._onPointerUp = function (e) {
  83034. if (this._joystickPointerID == e.pointerId) {
  83035. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  83036. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  83037. this._joystickPointerID = -1;
  83038. this.pressed = false;
  83039. }
  83040. else {
  83041. var touch = this._touches.get(e.pointerId.toString());
  83042. if (touch) {
  83043. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83044. }
  83045. }
  83046. this._deltaJoystickVector.x = 0;
  83047. this._deltaJoystickVector.y = 0;
  83048. this._touches.remove(e.pointerId.toString());
  83049. };
  83050. /**
  83051. * Change the color of the virtual joystick
  83052. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  83053. */
  83054. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  83055. this._joystickColor = newColor;
  83056. };
  83057. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  83058. this._action = action;
  83059. };
  83060. // Define which axis you'd like to control for left & right
  83061. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  83062. switch (axis) {
  83063. case JoystickAxis.X:
  83064. case JoystickAxis.Y:
  83065. case JoystickAxis.Z:
  83066. this._axisTargetedByLeftAndRight = axis;
  83067. break;
  83068. default:
  83069. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83070. break;
  83071. }
  83072. };
  83073. // Define which axis you'd like to control for up & down
  83074. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  83075. switch (axis) {
  83076. case JoystickAxis.X:
  83077. case JoystickAxis.Y:
  83078. case JoystickAxis.Z:
  83079. this._axisTargetedByUpAndDown = axis;
  83080. break;
  83081. default:
  83082. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83083. break;
  83084. }
  83085. };
  83086. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  83087. var _this = this;
  83088. if (this.pressed) {
  83089. this._touches.forEach(function (key, touch) {
  83090. if (touch.pointerId === _this._joystickPointerID) {
  83091. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  83092. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  83093. VirtualJoystick.vjCanvasContext.beginPath();
  83094. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83095. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83096. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  83097. VirtualJoystick.vjCanvasContext.stroke();
  83098. VirtualJoystick.vjCanvasContext.closePath();
  83099. VirtualJoystick.vjCanvasContext.beginPath();
  83100. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83101. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83102. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  83103. VirtualJoystick.vjCanvasContext.stroke();
  83104. VirtualJoystick.vjCanvasContext.closePath();
  83105. VirtualJoystick.vjCanvasContext.beginPath();
  83106. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83107. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  83108. VirtualJoystick.vjCanvasContext.stroke();
  83109. VirtualJoystick.vjCanvasContext.closePath();
  83110. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  83111. }
  83112. else {
  83113. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83114. VirtualJoystick.vjCanvasContext.beginPath();
  83115. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  83116. VirtualJoystick.vjCanvasContext.beginPath();
  83117. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  83118. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83119. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  83120. VirtualJoystick.vjCanvasContext.stroke();
  83121. VirtualJoystick.vjCanvasContext.closePath();
  83122. touch.prevX = touch.x;
  83123. touch.prevY = touch.y;
  83124. }
  83125. ;
  83126. });
  83127. }
  83128. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83129. };
  83130. VirtualJoystick.prototype.releaseCanvas = function () {
  83131. if (VirtualJoystick.vjCanvas) {
  83132. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  83133. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  83134. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  83135. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  83136. window.removeEventListener("resize", this._onResize);
  83137. document.body.removeChild(VirtualJoystick.vjCanvas);
  83138. VirtualJoystick.vjCanvas = null;
  83139. }
  83140. };
  83141. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  83142. VirtualJoystick._globalJoystickIndex = 0;
  83143. return VirtualJoystick;
  83144. }());
  83145. BABYLON.VirtualJoystick = VirtualJoystick;
  83146. })(BABYLON || (BABYLON = {}));
  83147. //# sourceMappingURL=babylon.virtualJoystick.js.map
  83148. var BABYLON;
  83149. (function (BABYLON) {
  83150. // We're mainly based on the logic defined into the FreeCamera code
  83151. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  83152. __extends(VirtualJoysticksCamera, _super);
  83153. function VirtualJoysticksCamera(name, position, scene) {
  83154. var _this = _super.call(this, name, position, scene) || this;
  83155. _this.inputs.addVirtualJoystick();
  83156. return _this;
  83157. }
  83158. VirtualJoysticksCamera.prototype.getClassName = function () {
  83159. return "VirtualJoysticksCamera";
  83160. };
  83161. return VirtualJoysticksCamera;
  83162. }(BABYLON.FreeCamera));
  83163. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  83164. })(BABYLON || (BABYLON = {}));
  83165. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  83166. var BABYLON;
  83167. (function (BABYLON) {
  83168. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  83169. function FreeCameraVirtualJoystickInput() {
  83170. }
  83171. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  83172. return this._leftjoystick;
  83173. };
  83174. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  83175. return this._rightjoystick;
  83176. };
  83177. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  83178. if (this._leftjoystick) {
  83179. var camera = this.camera;
  83180. var speed = camera._computeLocalCameraSpeed() * 50;
  83181. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  83182. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  83183. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  83184. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  83185. if (!this._leftjoystick.pressed) {
  83186. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  83187. }
  83188. if (!this._rightjoystick.pressed) {
  83189. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  83190. }
  83191. }
  83192. };
  83193. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  83194. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  83195. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  83196. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  83197. this._leftjoystick.setJoystickSensibility(0.15);
  83198. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  83199. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  83200. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  83201. this._rightjoystick.reverseUpDown = true;
  83202. this._rightjoystick.setJoystickSensibility(0.05);
  83203. this._rightjoystick.setJoystickColor("yellow");
  83204. };
  83205. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  83206. this._leftjoystick.releaseCanvas();
  83207. this._rightjoystick.releaseCanvas();
  83208. };
  83209. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  83210. return "FreeCameraVirtualJoystickInput";
  83211. };
  83212. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  83213. return "virtualJoystick";
  83214. };
  83215. return FreeCameraVirtualJoystickInput;
  83216. }());
  83217. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  83218. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  83219. })(BABYLON || (BABYLON = {}));
  83220. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  83221. var BABYLON;
  83222. (function (BABYLON) {
  83223. var SimplificationSettings = /** @class */ (function () {
  83224. function SimplificationSettings(quality, distance, optimizeMesh) {
  83225. this.quality = quality;
  83226. this.distance = distance;
  83227. this.optimizeMesh = optimizeMesh;
  83228. }
  83229. return SimplificationSettings;
  83230. }());
  83231. BABYLON.SimplificationSettings = SimplificationSettings;
  83232. var SimplificationQueue = /** @class */ (function () {
  83233. function SimplificationQueue() {
  83234. this.running = false;
  83235. this._simplificationArray = [];
  83236. }
  83237. SimplificationQueue.prototype.addTask = function (task) {
  83238. this._simplificationArray.push(task);
  83239. };
  83240. SimplificationQueue.prototype.executeNext = function () {
  83241. var task = this._simplificationArray.pop();
  83242. if (task) {
  83243. this.running = true;
  83244. this.runSimplification(task);
  83245. }
  83246. else {
  83247. this.running = false;
  83248. }
  83249. };
  83250. SimplificationQueue.prototype.runSimplification = function (task) {
  83251. var _this = this;
  83252. if (task.parallelProcessing) {
  83253. //parallel simplifier
  83254. task.settings.forEach(function (setting) {
  83255. var simplifier = _this.getSimplifier(task);
  83256. simplifier.simplify(setting, function (newMesh) {
  83257. task.mesh.addLODLevel(setting.distance, newMesh);
  83258. newMesh.isVisible = true;
  83259. //check if it is the last
  83260. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  83261. //all done, run the success callback.
  83262. task.successCallback();
  83263. }
  83264. _this.executeNext();
  83265. });
  83266. });
  83267. }
  83268. else {
  83269. //single simplifier.
  83270. var simplifier = this.getSimplifier(task);
  83271. var runDecimation = function (setting, callback) {
  83272. simplifier.simplify(setting, function (newMesh) {
  83273. task.mesh.addLODLevel(setting.distance, newMesh);
  83274. newMesh.isVisible = true;
  83275. //run the next quality level
  83276. callback();
  83277. });
  83278. };
  83279. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  83280. runDecimation(task.settings[loop.index], function () {
  83281. loop.executeNext();
  83282. });
  83283. }, function () {
  83284. //execution ended, run the success callback.
  83285. if (task.successCallback) {
  83286. task.successCallback();
  83287. }
  83288. _this.executeNext();
  83289. });
  83290. }
  83291. };
  83292. SimplificationQueue.prototype.getSimplifier = function (task) {
  83293. switch (task.simplificationType) {
  83294. case SimplificationType.QUADRATIC:
  83295. default:
  83296. return new QuadraticErrorSimplification(task.mesh);
  83297. }
  83298. };
  83299. return SimplificationQueue;
  83300. }());
  83301. BABYLON.SimplificationQueue = SimplificationQueue;
  83302. /**
  83303. * The implemented types of simplification.
  83304. * At the moment only Quadratic Error Decimation is implemented.
  83305. */
  83306. var SimplificationType;
  83307. (function (SimplificationType) {
  83308. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  83309. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  83310. var DecimationTriangle = /** @class */ (function () {
  83311. function DecimationTriangle(vertices) {
  83312. this.vertices = vertices;
  83313. this.error = new Array(4);
  83314. this.deleted = false;
  83315. this.isDirty = false;
  83316. this.deletePending = false;
  83317. this.borderFactor = 0;
  83318. }
  83319. return DecimationTriangle;
  83320. }());
  83321. BABYLON.DecimationTriangle = DecimationTriangle;
  83322. var DecimationVertex = /** @class */ (function () {
  83323. function DecimationVertex(position, id) {
  83324. this.position = position;
  83325. this.id = id;
  83326. this.isBorder = true;
  83327. this.q = new QuadraticMatrix();
  83328. this.triangleCount = 0;
  83329. this.triangleStart = 0;
  83330. this.originalOffsets = [];
  83331. }
  83332. DecimationVertex.prototype.updatePosition = function (newPosition) {
  83333. this.position.copyFrom(newPosition);
  83334. };
  83335. return DecimationVertex;
  83336. }());
  83337. BABYLON.DecimationVertex = DecimationVertex;
  83338. var QuadraticMatrix = /** @class */ (function () {
  83339. function QuadraticMatrix(data) {
  83340. this.data = new Array(10);
  83341. for (var i = 0; i < 10; ++i) {
  83342. if (data && data[i]) {
  83343. this.data[i] = data[i];
  83344. }
  83345. else {
  83346. this.data[i] = 0;
  83347. }
  83348. }
  83349. }
  83350. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  83351. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  83352. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  83353. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  83354. return det;
  83355. };
  83356. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  83357. for (var i = 0; i < 10; ++i) {
  83358. this.data[i] += matrix.data[i];
  83359. }
  83360. };
  83361. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  83362. for (var i = 0; i < 10; ++i) {
  83363. this.data[i] += data[i];
  83364. }
  83365. };
  83366. QuadraticMatrix.prototype.add = function (matrix) {
  83367. var m = new QuadraticMatrix();
  83368. for (var i = 0; i < 10; ++i) {
  83369. m.data[i] = this.data[i] + matrix.data[i];
  83370. }
  83371. return m;
  83372. };
  83373. QuadraticMatrix.FromData = function (a, b, c, d) {
  83374. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  83375. };
  83376. //returning an array to avoid garbage collection
  83377. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  83378. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  83379. };
  83380. return QuadraticMatrix;
  83381. }());
  83382. BABYLON.QuadraticMatrix = QuadraticMatrix;
  83383. var Reference = /** @class */ (function () {
  83384. function Reference(vertexId, triangleId) {
  83385. this.vertexId = vertexId;
  83386. this.triangleId = triangleId;
  83387. }
  83388. return Reference;
  83389. }());
  83390. BABYLON.Reference = Reference;
  83391. /**
  83392. * An implementation of the Quadratic Error simplification algorithm.
  83393. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  83394. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  83395. * @author RaananW
  83396. */
  83397. var QuadraticErrorSimplification = /** @class */ (function () {
  83398. function QuadraticErrorSimplification(_mesh) {
  83399. this._mesh = _mesh;
  83400. this.syncIterations = 5000;
  83401. this.aggressiveness = 7;
  83402. this.decimationIterations = 100;
  83403. this.boundingBoxEpsilon = BABYLON.Epsilon;
  83404. }
  83405. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  83406. var _this = this;
  83407. this.initDecimatedMesh();
  83408. //iterating through the submeshes array, one after the other.
  83409. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  83410. _this.initWithMesh(loop.index, function () {
  83411. _this.runDecimation(settings, loop.index, function () {
  83412. loop.executeNext();
  83413. });
  83414. }, settings.optimizeMesh);
  83415. }, function () {
  83416. setTimeout(function () {
  83417. successCallback(_this._reconstructedMesh);
  83418. }, 0);
  83419. });
  83420. };
  83421. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  83422. var _this = this;
  83423. var targetCount = ~~(this.triangles.length * settings.quality);
  83424. var deletedTriangles = 0;
  83425. var triangleCount = this.triangles.length;
  83426. var iterationFunction = function (iteration, callback) {
  83427. setTimeout(function () {
  83428. if (iteration % 5 === 0) {
  83429. _this.updateMesh(iteration === 0);
  83430. }
  83431. for (var i = 0; i < _this.triangles.length; ++i) {
  83432. _this.triangles[i].isDirty = false;
  83433. }
  83434. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  83435. var trianglesIterator = function (i) {
  83436. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  83437. var t = _this.triangles[tIdx];
  83438. if (!t)
  83439. return;
  83440. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  83441. return;
  83442. }
  83443. for (var j = 0; j < 3; ++j) {
  83444. if (t.error[j] < threshold) {
  83445. var deleted0 = [];
  83446. var deleted1 = [];
  83447. var v0 = t.vertices[j];
  83448. var v1 = t.vertices[(j + 1) % 3];
  83449. if (v0.isBorder || v1.isBorder)
  83450. continue;
  83451. var p = BABYLON.Vector3.Zero();
  83452. var n = BABYLON.Vector3.Zero();
  83453. var uv = BABYLON.Vector2.Zero();
  83454. var color = new BABYLON.Color4(0, 0, 0, 1);
  83455. _this.calculateError(v0, v1, p, n, uv, color);
  83456. var delTr = new Array();
  83457. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  83458. continue;
  83459. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  83460. continue;
  83461. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  83462. continue;
  83463. var uniqueArray = new Array();
  83464. delTr.forEach(function (deletedT) {
  83465. if (uniqueArray.indexOf(deletedT) === -1) {
  83466. deletedT.deletePending = true;
  83467. uniqueArray.push(deletedT);
  83468. }
  83469. });
  83470. if (uniqueArray.length % 2 !== 0) {
  83471. continue;
  83472. }
  83473. v0.q = v1.q.add(v0.q);
  83474. v0.updatePosition(p);
  83475. var tStart = _this.references.length;
  83476. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  83477. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  83478. var tCount = _this.references.length - tStart;
  83479. if (tCount <= v0.triangleCount) {
  83480. if (tCount) {
  83481. for (var c = 0; c < tCount; c++) {
  83482. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  83483. }
  83484. }
  83485. }
  83486. else {
  83487. v0.triangleStart = tStart;
  83488. }
  83489. v0.triangleCount = tCount;
  83490. break;
  83491. }
  83492. }
  83493. };
  83494. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  83495. }, 0);
  83496. };
  83497. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  83498. if (triangleCount - deletedTriangles <= targetCount)
  83499. loop.breakLoop();
  83500. else {
  83501. iterationFunction(loop.index, function () {
  83502. loop.executeNext();
  83503. });
  83504. }
  83505. }, function () {
  83506. setTimeout(function () {
  83507. //reconstruct this part of the mesh
  83508. _this.reconstructMesh(submeshIndex);
  83509. successCallback();
  83510. }, 0);
  83511. });
  83512. };
  83513. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  83514. var _this = this;
  83515. this.vertices = [];
  83516. this.triangles = [];
  83517. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83518. var indices = this._mesh.getIndices();
  83519. var submesh = this._mesh.subMeshes[submeshIndex];
  83520. var findInVertices = function (positionToSearch) {
  83521. if (optimizeMesh) {
  83522. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  83523. if (_this.vertices[ii].position.equals(positionToSearch)) {
  83524. return _this.vertices[ii];
  83525. }
  83526. }
  83527. }
  83528. return null;
  83529. };
  83530. var vertexReferences = [];
  83531. var vertexInit = function (i) {
  83532. if (!positionData) {
  83533. return;
  83534. }
  83535. var offset = i + submesh.verticesStart;
  83536. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  83537. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  83538. vertex.originalOffsets.push(offset);
  83539. if (vertex.id === _this.vertices.length) {
  83540. _this.vertices.push(vertex);
  83541. }
  83542. vertexReferences.push(vertex.id);
  83543. };
  83544. //var totalVertices = mesh.getTotalVertices();
  83545. var totalVertices = submesh.verticesCount;
  83546. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  83547. var indicesInit = function (i) {
  83548. if (!indices) {
  83549. return;
  83550. }
  83551. var offset = (submesh.indexStart / 3) + i;
  83552. var pos = (offset * 3);
  83553. var i0 = indices[pos + 0];
  83554. var i1 = indices[pos + 1];
  83555. var i2 = indices[pos + 2];
  83556. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  83557. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  83558. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  83559. var triangle = new DecimationTriangle([v0, v1, v2]);
  83560. triangle.originalOffset = pos;
  83561. _this.triangles.push(triangle);
  83562. };
  83563. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  83564. _this.init(callback);
  83565. });
  83566. });
  83567. };
  83568. QuadraticErrorSimplification.prototype.init = function (callback) {
  83569. var _this = this;
  83570. var triangleInit1 = function (i) {
  83571. var t = _this.triangles[i];
  83572. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  83573. for (var j = 0; j < 3; j++) {
  83574. 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))));
  83575. }
  83576. };
  83577. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  83578. var triangleInit2 = function (i) {
  83579. var t = _this.triangles[i];
  83580. for (var j = 0; j < 3; ++j) {
  83581. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  83582. }
  83583. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83584. };
  83585. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  83586. callback();
  83587. });
  83588. });
  83589. };
  83590. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  83591. var newTriangles = [];
  83592. var i;
  83593. for (i = 0; i < this.vertices.length; ++i) {
  83594. this.vertices[i].triangleCount = 0;
  83595. }
  83596. var t;
  83597. var j;
  83598. for (i = 0; i < this.triangles.length; ++i) {
  83599. if (!this.triangles[i].deleted) {
  83600. t = this.triangles[i];
  83601. for (j = 0; j < 3; ++j) {
  83602. t.vertices[j].triangleCount = 1;
  83603. }
  83604. newTriangles.push(t);
  83605. }
  83606. }
  83607. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  83608. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  83609. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  83610. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  83611. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  83612. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83613. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  83614. var vertexCount = 0;
  83615. for (i = 0; i < this.vertices.length; ++i) {
  83616. var vertex = this.vertices[i];
  83617. vertex.id = vertexCount;
  83618. if (vertex.triangleCount) {
  83619. vertex.originalOffsets.forEach(function (originalOffset) {
  83620. if (!normalData) {
  83621. return;
  83622. }
  83623. newPositionData.push(vertex.position.x);
  83624. newPositionData.push(vertex.position.y);
  83625. newPositionData.push(vertex.position.z);
  83626. newNormalData.push(normalData[originalOffset * 3]);
  83627. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  83628. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  83629. if (uvs && uvs.length) {
  83630. newUVsData.push(uvs[(originalOffset * 2)]);
  83631. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  83632. }
  83633. else if (colorsData && colorsData.length) {
  83634. newColorsData.push(colorsData[(originalOffset * 4)]);
  83635. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  83636. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  83637. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  83638. }
  83639. ++vertexCount;
  83640. });
  83641. }
  83642. }
  83643. var startingIndex = this._reconstructedMesh.getTotalIndices();
  83644. var startingVertex = this._reconstructedMesh.getTotalVertices();
  83645. var submeshesArray = this._reconstructedMesh.subMeshes;
  83646. this._reconstructedMesh.subMeshes = [];
  83647. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  83648. var originalIndices = this._mesh.getIndices();
  83649. for (i = 0; i < newTriangles.length; ++i) {
  83650. t = newTriangles[i]; //now get the new referencing point for each vertex
  83651. [0, 1, 2].forEach(function (idx) {
  83652. var id = originalIndices[t.originalOffset + idx];
  83653. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  83654. if (offset < 0)
  83655. offset = 0;
  83656. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  83657. });
  83658. }
  83659. //overwriting the old vertex buffers and indices.
  83660. this._reconstructedMesh.setIndices(newIndicesArray);
  83661. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  83662. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  83663. if (newUVsData.length > 0)
  83664. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  83665. if (newColorsData.length > 0)
  83666. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  83667. //create submesh
  83668. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  83669. if (submeshIndex > 0) {
  83670. this._reconstructedMesh.subMeshes = [];
  83671. submeshesArray.forEach(function (submesh) {
  83672. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  83673. });
  83674. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  83675. }
  83676. };
  83677. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  83678. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  83679. this._reconstructedMesh.material = this._mesh.material;
  83680. this._reconstructedMesh.parent = this._mesh.parent;
  83681. this._reconstructedMesh.isVisible = false;
  83682. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  83683. };
  83684. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  83685. for (var i = 0; i < vertex1.triangleCount; ++i) {
  83686. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  83687. if (t.deleted)
  83688. continue;
  83689. var s = this.references[vertex1.triangleStart + i].vertexId;
  83690. var v1 = t.vertices[(s + 1) % 3];
  83691. var v2 = t.vertices[(s + 2) % 3];
  83692. if ((v1 === vertex2 || v2 === vertex2)) {
  83693. deletedArray[i] = true;
  83694. delTr.push(t);
  83695. continue;
  83696. }
  83697. var d1 = v1.position.subtract(point);
  83698. d1 = d1.normalize();
  83699. var d2 = v2.position.subtract(point);
  83700. d2 = d2.normalize();
  83701. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  83702. return true;
  83703. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  83704. deletedArray[i] = false;
  83705. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  83706. return true;
  83707. }
  83708. return false;
  83709. };
  83710. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  83711. var newDeleted = deletedTriangles;
  83712. for (var i = 0; i < vertex.triangleCount; ++i) {
  83713. var ref = this.references[vertex.triangleStart + i];
  83714. var t = this.triangles[ref.triangleId];
  83715. if (t.deleted)
  83716. continue;
  83717. if (deletedArray[i] && t.deletePending) {
  83718. t.deleted = true;
  83719. newDeleted++;
  83720. continue;
  83721. }
  83722. t.vertices[ref.vertexId] = origVertex;
  83723. t.isDirty = true;
  83724. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  83725. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  83726. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  83727. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83728. this.references.push(ref);
  83729. }
  83730. return newDeleted;
  83731. };
  83732. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  83733. for (var i = 0; i < this.vertices.length; ++i) {
  83734. var vCount = [];
  83735. var vId = [];
  83736. var v = this.vertices[i];
  83737. var j;
  83738. for (j = 0; j < v.triangleCount; ++j) {
  83739. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  83740. for (var ii = 0; ii < 3; ii++) {
  83741. var ofs = 0;
  83742. var vv = triangle.vertices[ii];
  83743. while (ofs < vCount.length) {
  83744. if (vId[ofs] === vv.id)
  83745. break;
  83746. ++ofs;
  83747. }
  83748. if (ofs === vCount.length) {
  83749. vCount.push(1);
  83750. vId.push(vv.id);
  83751. }
  83752. else {
  83753. vCount[ofs]++;
  83754. }
  83755. }
  83756. }
  83757. for (j = 0; j < vCount.length; ++j) {
  83758. if (vCount[j] === 1) {
  83759. this.vertices[vId[j]].isBorder = true;
  83760. }
  83761. else {
  83762. this.vertices[vId[j]].isBorder = false;
  83763. }
  83764. }
  83765. }
  83766. };
  83767. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  83768. if (identifyBorders === void 0) { identifyBorders = false; }
  83769. var i;
  83770. if (!identifyBorders) {
  83771. var newTrianglesVector = [];
  83772. for (i = 0; i < this.triangles.length; ++i) {
  83773. if (!this.triangles[i].deleted) {
  83774. newTrianglesVector.push(this.triangles[i]);
  83775. }
  83776. }
  83777. this.triangles = newTrianglesVector;
  83778. }
  83779. for (i = 0; i < this.vertices.length; ++i) {
  83780. this.vertices[i].triangleCount = 0;
  83781. this.vertices[i].triangleStart = 0;
  83782. }
  83783. var t;
  83784. var j;
  83785. var v;
  83786. for (i = 0; i < this.triangles.length; ++i) {
  83787. t = this.triangles[i];
  83788. for (j = 0; j < 3; ++j) {
  83789. v = t.vertices[j];
  83790. v.triangleCount++;
  83791. }
  83792. }
  83793. var tStart = 0;
  83794. for (i = 0; i < this.vertices.length; ++i) {
  83795. this.vertices[i].triangleStart = tStart;
  83796. tStart += this.vertices[i].triangleCount;
  83797. this.vertices[i].triangleCount = 0;
  83798. }
  83799. var newReferences = new Array(this.triangles.length * 3);
  83800. for (i = 0; i < this.triangles.length; ++i) {
  83801. t = this.triangles[i];
  83802. for (j = 0; j < 3; ++j) {
  83803. v = t.vertices[j];
  83804. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  83805. v.triangleCount++;
  83806. }
  83807. }
  83808. this.references = newReferences;
  83809. if (identifyBorders) {
  83810. this.identifyBorder();
  83811. }
  83812. };
  83813. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  83814. var x = point.x;
  83815. var y = point.y;
  83816. var z = point.z;
  83817. 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
  83818. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  83819. };
  83820. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  83821. var q = vertex1.q.add(vertex2.q);
  83822. var border = vertex1.isBorder && vertex2.isBorder;
  83823. var error = 0;
  83824. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  83825. if (qDet !== 0 && !border) {
  83826. if (!pointResult) {
  83827. pointResult = BABYLON.Vector3.Zero();
  83828. }
  83829. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  83830. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  83831. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  83832. error = this.vertexError(q, pointResult);
  83833. }
  83834. else {
  83835. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  83836. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  83837. var error1 = this.vertexError(q, vertex1.position);
  83838. var error2 = this.vertexError(q, vertex2.position);
  83839. var error3 = this.vertexError(q, p3);
  83840. error = Math.min(error1, error2, error3);
  83841. if (error === error1) {
  83842. if (pointResult) {
  83843. pointResult.copyFrom(vertex1.position);
  83844. }
  83845. }
  83846. else if (error === error2) {
  83847. if (pointResult) {
  83848. pointResult.copyFrom(vertex2.position);
  83849. }
  83850. }
  83851. else {
  83852. if (pointResult) {
  83853. pointResult.copyFrom(p3);
  83854. }
  83855. }
  83856. }
  83857. return error;
  83858. };
  83859. return QuadraticErrorSimplification;
  83860. }());
  83861. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  83862. })(BABYLON || (BABYLON = {}));
  83863. //# sourceMappingURL=babylon.meshSimplification.js.map
  83864. var BABYLON;
  83865. (function (BABYLON) {
  83866. var MeshLODLevel = /** @class */ (function () {
  83867. function MeshLODLevel(distance, mesh) {
  83868. this.distance = distance;
  83869. this.mesh = mesh;
  83870. }
  83871. return MeshLODLevel;
  83872. }());
  83873. BABYLON.MeshLODLevel = MeshLODLevel;
  83874. })(BABYLON || (BABYLON = {}));
  83875. //# sourceMappingURL=babylon.meshLODLevel.js.map
  83876. var BABYLON;
  83877. (function (BABYLON) {
  83878. /**
  83879. * Defines the root class used to create scene optimization to use with SceneOptimizer
  83880. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83881. */
  83882. var SceneOptimization = /** @class */ (function () {
  83883. /**
  83884. * Creates the SceneOptimization object
  83885. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83886. * @param desc defines the description associated with the optimization
  83887. */
  83888. function SceneOptimization(
  83889. /**
  83890. * Defines the priority of this optimization (0 by default which means first in the list)
  83891. */
  83892. priority) {
  83893. if (priority === void 0) { priority = 0; }
  83894. this.priority = priority;
  83895. }
  83896. /**
  83897. * Gets a string describing the action executed by the current optimization
  83898. * @returns description string
  83899. */
  83900. SceneOptimization.prototype.getDescription = function () {
  83901. return "";
  83902. };
  83903. /**
  83904. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83905. * @param scene defines the current scene where to apply this optimization
  83906. * @param optimizer defines the current optimizer
  83907. * @returns true if everything that can be done was applied
  83908. */
  83909. SceneOptimization.prototype.apply = function (scene, optimizer) {
  83910. return true;
  83911. };
  83912. ;
  83913. return SceneOptimization;
  83914. }());
  83915. BABYLON.SceneOptimization = SceneOptimization;
  83916. /**
  83917. * Defines an optimization used to reduce the size of render target textures
  83918. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83919. */
  83920. var TextureOptimization = /** @class */ (function (_super) {
  83921. __extends(TextureOptimization, _super);
  83922. /**
  83923. * Creates the TextureOptimization object
  83924. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83925. * @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
  83926. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83927. */
  83928. function TextureOptimization(
  83929. /**
  83930. * Defines the priority of this optimization (0 by default which means first in the list)
  83931. */
  83932. priority,
  83933. /**
  83934. * 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
  83935. */
  83936. maximumSize,
  83937. /**
  83938. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83939. */
  83940. step) {
  83941. if (priority === void 0) { priority = 0; }
  83942. if (maximumSize === void 0) { maximumSize = 1024; }
  83943. if (step === void 0) { step = 0.5; }
  83944. var _this = _super.call(this, priority) || this;
  83945. _this.priority = priority;
  83946. _this.maximumSize = maximumSize;
  83947. _this.step = step;
  83948. return _this;
  83949. }
  83950. /**
  83951. * Gets a string describing the action executed by the current optimization
  83952. * @returns description string
  83953. */
  83954. TextureOptimization.prototype.getDescription = function () {
  83955. return "Reducing render target texture size to " + this.maximumSize;
  83956. };
  83957. /**
  83958. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83959. * @param scene defines the current scene where to apply this optimization
  83960. * @param optimizer defines the current optimizer
  83961. * @returns true if everything that can be done was applied
  83962. */
  83963. TextureOptimization.prototype.apply = function (scene, optimizer) {
  83964. var allDone = true;
  83965. for (var index = 0; index < scene.textures.length; index++) {
  83966. var texture = scene.textures[index];
  83967. if (!texture.canRescale || texture.getContext) {
  83968. continue;
  83969. }
  83970. var currentSize = texture.getSize();
  83971. var maxDimension = Math.max(currentSize.width, currentSize.height);
  83972. if (maxDimension > this.maximumSize) {
  83973. texture.scale(this.step);
  83974. allDone = false;
  83975. }
  83976. }
  83977. return allDone;
  83978. };
  83979. return TextureOptimization;
  83980. }(SceneOptimization));
  83981. BABYLON.TextureOptimization = TextureOptimization;
  83982. /**
  83983. * Defines an optimization used to increase or decrease the rendering resolution
  83984. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83985. */
  83986. var HardwareScalingOptimization = /** @class */ (function (_super) {
  83987. __extends(HardwareScalingOptimization, _super);
  83988. /**
  83989. * Creates the HardwareScalingOptimization object
  83990. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83991. * @param maximumScale defines the maximum scale to use (2 by default)
  83992. * @param step defines the step to use between two passes (0.5 by default)
  83993. */
  83994. function HardwareScalingOptimization(
  83995. /**
  83996. * Defines the priority of this optimization (0 by default which means first in the list)
  83997. */
  83998. priority,
  83999. /**
  84000. * Defines the maximum scale to use (2 by default)
  84001. */
  84002. maximumScale,
  84003. /**
  84004. * Defines the step to use between two passes (0.5 by default)
  84005. */
  84006. step) {
  84007. if (priority === void 0) { priority = 0; }
  84008. if (maximumScale === void 0) { maximumScale = 2; }
  84009. if (step === void 0) { step = 0.25; }
  84010. var _this = _super.call(this, priority) || this;
  84011. _this.priority = priority;
  84012. _this.maximumScale = maximumScale;
  84013. _this.step = step;
  84014. _this._currentScale = -1;
  84015. _this._directionOffset = 1;
  84016. return _this;
  84017. }
  84018. /**
  84019. * Gets a string describing the action executed by the current optimization
  84020. * @return description string
  84021. */
  84022. HardwareScalingOptimization.prototype.getDescription = function () {
  84023. return "Setting hardware scaling level to " + this._currentScale;
  84024. };
  84025. /**
  84026. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84027. * @param scene defines the current scene where to apply this optimization
  84028. * @param optimizer defines the current optimizer
  84029. * @returns true if everything that can be done was applied
  84030. */
  84031. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  84032. if (this._currentScale === -1) {
  84033. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  84034. if (this._currentScale > this.maximumScale) {
  84035. this._directionOffset = -1;
  84036. }
  84037. }
  84038. this._currentScale += this._directionOffset * this.step;
  84039. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  84040. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  84041. };
  84042. ;
  84043. return HardwareScalingOptimization;
  84044. }(SceneOptimization));
  84045. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  84046. /**
  84047. * Defines an optimization used to remove shadows
  84048. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84049. */
  84050. var ShadowsOptimization = /** @class */ (function (_super) {
  84051. __extends(ShadowsOptimization, _super);
  84052. function ShadowsOptimization() {
  84053. return _super !== null && _super.apply(this, arguments) || this;
  84054. }
  84055. /**
  84056. * Gets a string describing the action executed by the current optimization
  84057. * @return description string
  84058. */
  84059. ShadowsOptimization.prototype.getDescription = function () {
  84060. return "Turning shadows on/off";
  84061. };
  84062. /**
  84063. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84064. * @param scene defines the current scene where to apply this optimization
  84065. * @param optimizer defines the current optimizer
  84066. * @returns true if everything that can be done was applied
  84067. */
  84068. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  84069. scene.shadowsEnabled = optimizer.isInImprovementMode;
  84070. return true;
  84071. };
  84072. ;
  84073. return ShadowsOptimization;
  84074. }(SceneOptimization));
  84075. BABYLON.ShadowsOptimization = ShadowsOptimization;
  84076. /**
  84077. * Defines an optimization used to turn post-processes off
  84078. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84079. */
  84080. var PostProcessesOptimization = /** @class */ (function (_super) {
  84081. __extends(PostProcessesOptimization, _super);
  84082. function PostProcessesOptimization() {
  84083. return _super !== null && _super.apply(this, arguments) || this;
  84084. }
  84085. /**
  84086. * Gets a string describing the action executed by the current optimization
  84087. * @return description string
  84088. */
  84089. PostProcessesOptimization.prototype.getDescription = function () {
  84090. return "Turning post-processes on/off";
  84091. };
  84092. /**
  84093. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84094. * @param scene defines the current scene where to apply this optimization
  84095. * @param optimizer defines the current optimizer
  84096. * @returns true if everything that can be done was applied
  84097. */
  84098. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  84099. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  84100. return true;
  84101. };
  84102. ;
  84103. return PostProcessesOptimization;
  84104. }(SceneOptimization));
  84105. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  84106. /**
  84107. * Defines an optimization used to turn lens flares off
  84108. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84109. */
  84110. var LensFlaresOptimization = /** @class */ (function (_super) {
  84111. __extends(LensFlaresOptimization, _super);
  84112. function LensFlaresOptimization() {
  84113. return _super !== null && _super.apply(this, arguments) || this;
  84114. }
  84115. /**
  84116. * Gets a string describing the action executed by the current optimization
  84117. * @return description string
  84118. */
  84119. LensFlaresOptimization.prototype.getDescription = function () {
  84120. return "Turning lens flares on/off";
  84121. };
  84122. /**
  84123. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84124. * @param scene defines the current scene where to apply this optimization
  84125. * @param optimizer defines the current optimizer
  84126. * @returns true if everything that can be done was applied
  84127. */
  84128. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  84129. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  84130. return true;
  84131. };
  84132. ;
  84133. return LensFlaresOptimization;
  84134. }(SceneOptimization));
  84135. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  84136. /**
  84137. * Defines an optimization based on user defined callback.
  84138. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84139. */
  84140. var CustomOptimization = /** @class */ (function (_super) {
  84141. __extends(CustomOptimization, _super);
  84142. function CustomOptimization() {
  84143. return _super !== null && _super.apply(this, arguments) || this;
  84144. }
  84145. /**
  84146. * Gets a string describing the action executed by the current optimization
  84147. * @returns description string
  84148. */
  84149. CustomOptimization.prototype.getDescription = function () {
  84150. if (this.onGetDescription) {
  84151. return this.onGetDescription();
  84152. }
  84153. return "Running user defined callback";
  84154. };
  84155. /**
  84156. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84157. * @param scene defines the current scene where to apply this optimization
  84158. * @param optimizer defines the current optimizer
  84159. * @returns true if everything that can be done was applied
  84160. */
  84161. CustomOptimization.prototype.apply = function (scene, optimizer) {
  84162. if (this.onApply) {
  84163. return this.onApply(scene, optimizer);
  84164. }
  84165. return true;
  84166. };
  84167. ;
  84168. return CustomOptimization;
  84169. }(SceneOptimization));
  84170. BABYLON.CustomOptimization = CustomOptimization;
  84171. /**
  84172. * Defines an optimization used to turn particles off
  84173. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84174. */
  84175. var ParticlesOptimization = /** @class */ (function (_super) {
  84176. __extends(ParticlesOptimization, _super);
  84177. function ParticlesOptimization() {
  84178. return _super !== null && _super.apply(this, arguments) || this;
  84179. }
  84180. /**
  84181. * Gets a string describing the action executed by the current optimization
  84182. * @return description string
  84183. */
  84184. ParticlesOptimization.prototype.getDescription = function () {
  84185. return "Turning particles on/off";
  84186. };
  84187. /**
  84188. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84189. * @param scene defines the current scene where to apply this optimization
  84190. * @param optimizer defines the current optimizer
  84191. * @returns true if everything that can be done was applied
  84192. */
  84193. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  84194. scene.particlesEnabled = optimizer.isInImprovementMode;
  84195. return true;
  84196. };
  84197. ;
  84198. return ParticlesOptimization;
  84199. }(SceneOptimization));
  84200. BABYLON.ParticlesOptimization = ParticlesOptimization;
  84201. /**
  84202. * Defines an optimization used to turn render targets off
  84203. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84204. */
  84205. var RenderTargetsOptimization = /** @class */ (function (_super) {
  84206. __extends(RenderTargetsOptimization, _super);
  84207. function RenderTargetsOptimization() {
  84208. return _super !== null && _super.apply(this, arguments) || this;
  84209. }
  84210. /**
  84211. * Gets a string describing the action executed by the current optimization
  84212. * @return description string
  84213. */
  84214. RenderTargetsOptimization.prototype.getDescription = function () {
  84215. return "Turning render targets off";
  84216. };
  84217. /**
  84218. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84219. * @param scene defines the current scene where to apply this optimization
  84220. * @param optimizer defines the current optimizer
  84221. * @returns true if everything that can be done was applied
  84222. */
  84223. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  84224. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  84225. return true;
  84226. };
  84227. ;
  84228. return RenderTargetsOptimization;
  84229. }(SceneOptimization));
  84230. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  84231. /**
  84232. * Defines an optimization used to merge meshes with compatible materials
  84233. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84234. */
  84235. var MergeMeshesOptimization = /** @class */ (function (_super) {
  84236. __extends(MergeMeshesOptimization, _super);
  84237. function MergeMeshesOptimization() {
  84238. var _this = _super !== null && _super.apply(this, arguments) || this;
  84239. _this._canBeMerged = function (abstractMesh) {
  84240. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  84241. return false;
  84242. }
  84243. var mesh = abstractMesh;
  84244. if (!mesh.isVisible || !mesh.isEnabled()) {
  84245. return false;
  84246. }
  84247. if (mesh.instances.length > 0) {
  84248. return false;
  84249. }
  84250. if (mesh.skeleton || mesh.hasLODLevels) {
  84251. return false;
  84252. }
  84253. if (mesh.parent) {
  84254. return false;
  84255. }
  84256. return true;
  84257. };
  84258. return _this;
  84259. }
  84260. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  84261. /**
  84262. * Gets or sets a boolean which defines if optimization octree has to be updated
  84263. */
  84264. get: function () {
  84265. return MergeMeshesOptimization._UpdateSelectionTree;
  84266. },
  84267. /**
  84268. * Gets or sets a boolean which defines if optimization octree has to be updated
  84269. */
  84270. set: function (value) {
  84271. MergeMeshesOptimization._UpdateSelectionTree = value;
  84272. },
  84273. enumerable: true,
  84274. configurable: true
  84275. });
  84276. /**
  84277. * Gets a string describing the action executed by the current optimization
  84278. * @return description string
  84279. */
  84280. MergeMeshesOptimization.prototype.getDescription = function () {
  84281. return "Merging similar meshes together";
  84282. };
  84283. /**
  84284. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84285. * @param scene defines the current scene where to apply this optimization
  84286. * @param optimizer defines the current optimizer
  84287. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  84288. * @returns true if everything that can be done was applied
  84289. */
  84290. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  84291. var globalPool = scene.meshes.slice(0);
  84292. var globalLength = globalPool.length;
  84293. for (var index = 0; index < globalLength; index++) {
  84294. var currentPool = new Array();
  84295. var current = globalPool[index];
  84296. // Checks
  84297. if (!this._canBeMerged(current)) {
  84298. continue;
  84299. }
  84300. currentPool.push(current);
  84301. // Find compatible meshes
  84302. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  84303. var otherMesh = globalPool[subIndex];
  84304. if (!this._canBeMerged(otherMesh)) {
  84305. continue;
  84306. }
  84307. if (otherMesh.material !== current.material) {
  84308. continue;
  84309. }
  84310. if (otherMesh.checkCollisions !== current.checkCollisions) {
  84311. continue;
  84312. }
  84313. currentPool.push(otherMesh);
  84314. globalLength--;
  84315. globalPool.splice(subIndex, 1);
  84316. subIndex--;
  84317. }
  84318. if (currentPool.length < 2) {
  84319. continue;
  84320. }
  84321. // Merge meshes
  84322. BABYLON.Mesh.MergeMeshes(currentPool);
  84323. }
  84324. if (updateSelectionTree != undefined) {
  84325. if (updateSelectionTree) {
  84326. scene.createOrUpdateSelectionOctree();
  84327. }
  84328. }
  84329. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  84330. scene.createOrUpdateSelectionOctree();
  84331. }
  84332. return true;
  84333. };
  84334. ;
  84335. MergeMeshesOptimization._UpdateSelectionTree = false;
  84336. return MergeMeshesOptimization;
  84337. }(SceneOptimization));
  84338. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  84339. /**
  84340. * Defines a list of options used by SceneOptimizer
  84341. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84342. */
  84343. var SceneOptimizerOptions = /** @class */ (function () {
  84344. /**
  84345. * Creates a new list of options used by SceneOptimizer
  84346. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  84347. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  84348. */
  84349. function SceneOptimizerOptions(
  84350. /**
  84351. * Defines the target frame rate to reach (60 by default)
  84352. */
  84353. targetFrameRate,
  84354. /**
  84355. * Defines the interval between two checkes (2000ms by default)
  84356. */
  84357. trackerDuration) {
  84358. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  84359. if (trackerDuration === void 0) { trackerDuration = 2000; }
  84360. this.targetFrameRate = targetFrameRate;
  84361. this.trackerDuration = trackerDuration;
  84362. /**
  84363. * Gets the list of optimizations to apply
  84364. */
  84365. this.optimizations = new Array();
  84366. }
  84367. /**
  84368. * Add a new optimization
  84369. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  84370. * @returns the current SceneOptimizerOptions
  84371. */
  84372. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  84373. this.optimizations.push(optimization);
  84374. return this;
  84375. };
  84376. /**
  84377. * Add a new custom optimization
  84378. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  84379. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  84380. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84381. * @returns the current SceneOptimizerOptions
  84382. */
  84383. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  84384. if (priority === void 0) { priority = 0; }
  84385. var optimization = new CustomOptimization(priority);
  84386. optimization.onApply = onApply;
  84387. optimization.onGetDescription = onGetDescription;
  84388. this.optimizations.push(optimization);
  84389. return this;
  84390. };
  84391. /**
  84392. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  84393. * @param targetFrameRate defines the target frame rate (60 by default)
  84394. * @returns a SceneOptimizerOptions object
  84395. */
  84396. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  84397. var result = new SceneOptimizerOptions(targetFrameRate);
  84398. var priority = 0;
  84399. result.addOptimization(new MergeMeshesOptimization(priority));
  84400. result.addOptimization(new ShadowsOptimization(priority));
  84401. result.addOptimization(new LensFlaresOptimization(priority));
  84402. // Next priority
  84403. priority++;
  84404. result.addOptimization(new PostProcessesOptimization(priority));
  84405. result.addOptimization(new ParticlesOptimization(priority));
  84406. // Next priority
  84407. priority++;
  84408. result.addOptimization(new TextureOptimization(priority, 1024));
  84409. return result;
  84410. };
  84411. /**
  84412. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  84413. * @param targetFrameRate defines the target frame rate (60 by default)
  84414. * @returns a SceneOptimizerOptions object
  84415. */
  84416. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  84417. var result = new SceneOptimizerOptions(targetFrameRate);
  84418. var priority = 0;
  84419. result.addOptimization(new MergeMeshesOptimization(priority));
  84420. result.addOptimization(new ShadowsOptimization(priority));
  84421. result.addOptimization(new LensFlaresOptimization(priority));
  84422. // Next priority
  84423. priority++;
  84424. result.addOptimization(new PostProcessesOptimization(priority));
  84425. result.addOptimization(new ParticlesOptimization(priority));
  84426. // Next priority
  84427. priority++;
  84428. result.addOptimization(new TextureOptimization(priority, 512));
  84429. // Next priority
  84430. priority++;
  84431. result.addOptimization(new RenderTargetsOptimization(priority));
  84432. // Next priority
  84433. priority++;
  84434. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  84435. return result;
  84436. };
  84437. /**
  84438. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  84439. * @param targetFrameRate defines the target frame rate (60 by default)
  84440. * @returns a SceneOptimizerOptions object
  84441. */
  84442. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  84443. var result = new SceneOptimizerOptions(targetFrameRate);
  84444. var priority = 0;
  84445. result.addOptimization(new MergeMeshesOptimization(priority));
  84446. result.addOptimization(new ShadowsOptimization(priority));
  84447. result.addOptimization(new LensFlaresOptimization(priority));
  84448. // Next priority
  84449. priority++;
  84450. result.addOptimization(new PostProcessesOptimization(priority));
  84451. result.addOptimization(new ParticlesOptimization(priority));
  84452. // Next priority
  84453. priority++;
  84454. result.addOptimization(new TextureOptimization(priority, 256));
  84455. // Next priority
  84456. priority++;
  84457. result.addOptimization(new RenderTargetsOptimization(priority));
  84458. // Next priority
  84459. priority++;
  84460. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  84461. return result;
  84462. };
  84463. return SceneOptimizerOptions;
  84464. }());
  84465. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  84466. /**
  84467. * Class used to run optimizations in order to reach a target frame rate
  84468. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84469. */
  84470. var SceneOptimizer = /** @class */ (function () {
  84471. /**
  84472. * Creates a new SceneOptimizer
  84473. * @param scene defines the scene to work on
  84474. * @param options defines the options to use with the SceneOptimizer
  84475. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  84476. * @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)
  84477. */
  84478. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  84479. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  84480. if (improvementMode === void 0) { improvementMode = false; }
  84481. var _this = this;
  84482. this._isRunning = false;
  84483. this._currentPriorityLevel = 0;
  84484. this._targetFrameRate = 60;
  84485. this._trackerDuration = 2000;
  84486. this._currentFrameRate = 0;
  84487. this._improvementMode = false;
  84488. /**
  84489. * Defines an observable called when the optimizer reaches the target frame rate
  84490. */
  84491. this.onSuccessObservable = new BABYLON.Observable();
  84492. /**
  84493. * Defines an observable called when the optimizer enables an optimization
  84494. */
  84495. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  84496. /**
  84497. * Defines an observable called when the optimizer is not able to reach the target frame rate
  84498. */
  84499. this.onFailureObservable = new BABYLON.Observable();
  84500. if (!options) {
  84501. this._options = new SceneOptimizerOptions();
  84502. }
  84503. else {
  84504. this._options = options;
  84505. }
  84506. if (this._options.targetFrameRate) {
  84507. this._targetFrameRate = this._options.targetFrameRate;
  84508. }
  84509. if (this._options.trackerDuration) {
  84510. this._trackerDuration = this._options.trackerDuration;
  84511. }
  84512. if (autoGeneratePriorities) {
  84513. var priority = 0;
  84514. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  84515. var optim = _a[_i];
  84516. optim.priority = priority++;
  84517. }
  84518. }
  84519. this._improvementMode = improvementMode;
  84520. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84521. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  84522. _this._sceneDisposeObserver = null;
  84523. _this.dispose();
  84524. });
  84525. }
  84526. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  84527. /**
  84528. * Gets a boolean indicating if the optimizer is in improvement mode
  84529. */
  84530. get: function () {
  84531. return this._improvementMode;
  84532. },
  84533. enumerable: true,
  84534. configurable: true
  84535. });
  84536. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  84537. /**
  84538. * Gets the current priority level (0 at start)
  84539. */
  84540. get: function () {
  84541. return this._currentPriorityLevel;
  84542. },
  84543. enumerable: true,
  84544. configurable: true
  84545. });
  84546. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  84547. /**
  84548. * Gets the current frame rate checked by the SceneOptimizer
  84549. */
  84550. get: function () {
  84551. return this._currentFrameRate;
  84552. },
  84553. enumerable: true,
  84554. configurable: true
  84555. });
  84556. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  84557. /**
  84558. * Gets or sets the current target frame rate (60 by default)
  84559. */
  84560. get: function () {
  84561. return this._targetFrameRate;
  84562. },
  84563. /**
  84564. * Gets or sets the current target frame rate (60 by default)
  84565. */
  84566. set: function (value) {
  84567. this._targetFrameRate = value;
  84568. },
  84569. enumerable: true,
  84570. configurable: true
  84571. });
  84572. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  84573. /**
  84574. * Gets or sets the current interval between two checks (every 2000ms by default)
  84575. */
  84576. get: function () {
  84577. return this._trackerDuration;
  84578. },
  84579. /**
  84580. * Gets or sets the current interval between two checks (every 2000ms by default)
  84581. */
  84582. set: function (value) {
  84583. this._trackerDuration = value;
  84584. },
  84585. enumerable: true,
  84586. configurable: true
  84587. });
  84588. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  84589. /**
  84590. * Gets the list of active optimizations
  84591. */
  84592. get: function () {
  84593. return this._options.optimizations;
  84594. },
  84595. enumerable: true,
  84596. configurable: true
  84597. });
  84598. /**
  84599. * Stops the current optimizer
  84600. */
  84601. SceneOptimizer.prototype.stop = function () {
  84602. this._isRunning = false;
  84603. };
  84604. /**
  84605. * Reset the optimizer to initial step (current priority level = 0)
  84606. */
  84607. SceneOptimizer.prototype.reset = function () {
  84608. this._currentPriorityLevel = 0;
  84609. };
  84610. /**
  84611. * Start the optimizer. By default it will try to reach a specific framerate
  84612. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  84613. */
  84614. SceneOptimizer.prototype.start = function () {
  84615. var _this = this;
  84616. if (this._isRunning) {
  84617. return;
  84618. }
  84619. this._isRunning = true;
  84620. // Let's wait for the scene to be ready before running our check
  84621. this._scene.executeWhenReady(function () {
  84622. setTimeout(function () {
  84623. _this._checkCurrentState();
  84624. }, _this._trackerDuration);
  84625. });
  84626. };
  84627. SceneOptimizer.prototype._checkCurrentState = function () {
  84628. var _this = this;
  84629. if (!this._isRunning) {
  84630. return;
  84631. }
  84632. var scene = this._scene;
  84633. var options = this._options;
  84634. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  84635. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  84636. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  84637. this._isRunning = false;
  84638. this.onSuccessObservable.notifyObservers(this);
  84639. return;
  84640. }
  84641. // Apply current level of optimizations
  84642. var allDone = true;
  84643. var noOptimizationApplied = true;
  84644. for (var index = 0; index < options.optimizations.length; index++) {
  84645. var optimization = options.optimizations[index];
  84646. if (optimization.priority === this._currentPriorityLevel) {
  84647. noOptimizationApplied = false;
  84648. allDone = allDone && optimization.apply(scene, this);
  84649. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  84650. }
  84651. }
  84652. // If no optimization was applied, this is a failure :(
  84653. if (noOptimizationApplied) {
  84654. this._isRunning = false;
  84655. this.onFailureObservable.notifyObservers(this);
  84656. return;
  84657. }
  84658. // If all optimizations were done, move to next level
  84659. if (allDone) {
  84660. this._currentPriorityLevel++;
  84661. }
  84662. // Let's the system running for a specific amount of time before checking FPS
  84663. scene.executeWhenReady(function () {
  84664. setTimeout(function () {
  84665. _this._checkCurrentState();
  84666. }, _this._trackerDuration);
  84667. });
  84668. };
  84669. /**
  84670. * Release all resources
  84671. */
  84672. SceneOptimizer.prototype.dispose = function () {
  84673. this.stop();
  84674. this.onSuccessObservable.clear();
  84675. this.onFailureObservable.clear();
  84676. this.onNewOptimizationAppliedObservable.clear();
  84677. if (this._sceneDisposeObserver) {
  84678. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  84679. }
  84680. };
  84681. /**
  84682. * Helper function to create a SceneOptimizer with one single line of code
  84683. * @param scene defines the scene to work on
  84684. * @param options defines the options to use with the SceneOptimizer
  84685. * @param onSuccess defines a callback to call on success
  84686. * @param onFailure defines a callback to call on failure
  84687. * @returns the new SceneOptimizer object
  84688. */
  84689. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  84690. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  84691. if (onSuccess) {
  84692. optimizer.onSuccessObservable.add(function () {
  84693. onSuccess();
  84694. });
  84695. }
  84696. if (onFailure) {
  84697. optimizer.onFailureObservable.add(function () {
  84698. onFailure();
  84699. });
  84700. }
  84701. optimizer.start();
  84702. return optimizer;
  84703. };
  84704. return SceneOptimizer;
  84705. }());
  84706. BABYLON.SceneOptimizer = SceneOptimizer;
  84707. })(BABYLON || (BABYLON = {}));
  84708. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  84709. var BABYLON;
  84710. (function (BABYLON) {
  84711. var OutlineRenderer = /** @class */ (function () {
  84712. function OutlineRenderer(scene) {
  84713. this.zOffset = 1;
  84714. this._scene = scene;
  84715. }
  84716. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  84717. var _this = this;
  84718. if (useOverlay === void 0) { useOverlay = false; }
  84719. var scene = this._scene;
  84720. var engine = this._scene.getEngine();
  84721. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84722. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  84723. return;
  84724. }
  84725. var mesh = subMesh.getRenderingMesh();
  84726. var material = subMesh.getMaterial();
  84727. if (!material || !scene.activeCamera) {
  84728. return;
  84729. }
  84730. engine.enableEffect(this._effect);
  84731. // Logarithmic depth
  84732. if (material.useLogarithmicDepth) {
  84733. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  84734. }
  84735. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  84736. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  84737. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84738. // Bones
  84739. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84740. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84741. }
  84742. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  84743. // Alpha test
  84744. if (material && material.needAlphaTesting()) {
  84745. var alphaTexture = material.getAlphaTestTexture();
  84746. if (alphaTexture) {
  84747. this._effect.setTexture("diffuseSampler", alphaTexture);
  84748. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84749. }
  84750. }
  84751. engine.setZOffset(-this.zOffset);
  84752. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  84753. engine.setZOffset(0);
  84754. };
  84755. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  84756. var defines = [];
  84757. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84758. var mesh = subMesh.getMesh();
  84759. var material = subMesh.getMaterial();
  84760. if (material) {
  84761. // Alpha test
  84762. if (material.needAlphaTesting()) {
  84763. defines.push("#define ALPHATEST");
  84764. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84765. attribs.push(BABYLON.VertexBuffer.UVKind);
  84766. defines.push("#define UV1");
  84767. }
  84768. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84769. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84770. defines.push("#define UV2");
  84771. }
  84772. }
  84773. //Logarithmic depth
  84774. if (material.useLogarithmicDepth) {
  84775. defines.push("#define LOGARITHMICDEPTH");
  84776. }
  84777. }
  84778. // Bones
  84779. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84780. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84781. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84782. if (mesh.numBoneInfluencers > 4) {
  84783. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84784. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84785. }
  84786. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84787. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84788. }
  84789. else {
  84790. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84791. }
  84792. // Instances
  84793. if (useInstances) {
  84794. defines.push("#define INSTANCES");
  84795. attribs.push("world0");
  84796. attribs.push("world1");
  84797. attribs.push("world2");
  84798. attribs.push("world3");
  84799. }
  84800. // Get correct effect
  84801. var join = defines.join("\n");
  84802. if (this._cachedDefines !== join) {
  84803. this._cachedDefines = join;
  84804. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  84805. }
  84806. return this._effect.isReady();
  84807. };
  84808. return OutlineRenderer;
  84809. }());
  84810. BABYLON.OutlineRenderer = OutlineRenderer;
  84811. })(BABYLON || (BABYLON = {}));
  84812. //# sourceMappingURL=babylon.outlineRenderer.js.map
  84813. var BABYLON;
  84814. (function (BABYLON) {
  84815. var FaceAdjacencies = /** @class */ (function () {
  84816. function FaceAdjacencies() {
  84817. this.edges = new Array();
  84818. this.edgesConnectedCount = 0;
  84819. }
  84820. return FaceAdjacencies;
  84821. }());
  84822. var EdgesRenderer = /** @class */ (function () {
  84823. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  84824. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  84825. if (epsilon === void 0) { epsilon = 0.95; }
  84826. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  84827. this.edgesWidthScalerForOrthographic = 1000.0;
  84828. this.edgesWidthScalerForPerspective = 50.0;
  84829. this._linesPositions = new Array();
  84830. this._linesNormals = new Array();
  84831. this._linesIndices = new Array();
  84832. this._buffers = {};
  84833. this._checkVerticesInsteadOfIndices = false;
  84834. this._source = source;
  84835. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  84836. this._epsilon = epsilon;
  84837. this._prepareRessources();
  84838. this._generateEdgesLines();
  84839. }
  84840. EdgesRenderer.prototype._prepareRessources = function () {
  84841. if (this._lineShader) {
  84842. return;
  84843. }
  84844. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  84845. attributes: ["position", "normal"],
  84846. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  84847. });
  84848. this._lineShader.disableDepthWrite = true;
  84849. this._lineShader.backFaceCulling = false;
  84850. };
  84851. EdgesRenderer.prototype._rebuild = function () {
  84852. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84853. if (buffer) {
  84854. buffer._rebuild();
  84855. }
  84856. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84857. if (buffer) {
  84858. buffer._rebuild();
  84859. }
  84860. var scene = this._source.getScene();
  84861. var engine = scene.getEngine();
  84862. this._ib = engine.createIndexBuffer(this._linesIndices);
  84863. };
  84864. EdgesRenderer.prototype.dispose = function () {
  84865. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84866. if (buffer) {
  84867. buffer.dispose();
  84868. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  84869. }
  84870. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84871. if (buffer) {
  84872. buffer.dispose();
  84873. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  84874. }
  84875. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  84876. this._lineShader.dispose();
  84877. };
  84878. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  84879. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  84880. return 0;
  84881. }
  84882. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  84883. return 1;
  84884. }
  84885. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  84886. return 2;
  84887. }
  84888. return -1;
  84889. };
  84890. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  84891. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  84892. return 0;
  84893. }
  84894. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  84895. return 1;
  84896. }
  84897. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  84898. return 2;
  84899. }
  84900. return -1;
  84901. };
  84902. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  84903. var needToCreateLine;
  84904. if (edge === undefined) {
  84905. needToCreateLine = true;
  84906. }
  84907. else {
  84908. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  84909. needToCreateLine = dotProduct < this._epsilon;
  84910. }
  84911. if (needToCreateLine) {
  84912. var offset = this._linesPositions.length / 3;
  84913. var normal = p0.subtract(p1);
  84914. normal.normalize();
  84915. // Positions
  84916. this._linesPositions.push(p0.x);
  84917. this._linesPositions.push(p0.y);
  84918. this._linesPositions.push(p0.z);
  84919. this._linesPositions.push(p0.x);
  84920. this._linesPositions.push(p0.y);
  84921. this._linesPositions.push(p0.z);
  84922. this._linesPositions.push(p1.x);
  84923. this._linesPositions.push(p1.y);
  84924. this._linesPositions.push(p1.z);
  84925. this._linesPositions.push(p1.x);
  84926. this._linesPositions.push(p1.y);
  84927. this._linesPositions.push(p1.z);
  84928. // Normals
  84929. this._linesNormals.push(p1.x);
  84930. this._linesNormals.push(p1.y);
  84931. this._linesNormals.push(p1.z);
  84932. this._linesNormals.push(-1);
  84933. this._linesNormals.push(p1.x);
  84934. this._linesNormals.push(p1.y);
  84935. this._linesNormals.push(p1.z);
  84936. this._linesNormals.push(1);
  84937. this._linesNormals.push(p0.x);
  84938. this._linesNormals.push(p0.y);
  84939. this._linesNormals.push(p0.z);
  84940. this._linesNormals.push(-1);
  84941. this._linesNormals.push(p0.x);
  84942. this._linesNormals.push(p0.y);
  84943. this._linesNormals.push(p0.z);
  84944. this._linesNormals.push(1);
  84945. // Indices
  84946. this._linesIndices.push(offset);
  84947. this._linesIndices.push(offset + 1);
  84948. this._linesIndices.push(offset + 2);
  84949. this._linesIndices.push(offset);
  84950. this._linesIndices.push(offset + 2);
  84951. this._linesIndices.push(offset + 3);
  84952. }
  84953. };
  84954. EdgesRenderer.prototype._generateEdgesLines = function () {
  84955. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84956. var indices = this._source.getIndices();
  84957. if (!indices || !positions) {
  84958. return;
  84959. }
  84960. // First let's find adjacencies
  84961. var adjacencies = new Array();
  84962. var faceNormals = new Array();
  84963. var index;
  84964. var faceAdjacencies;
  84965. // Prepare faces
  84966. for (index = 0; index < indices.length; index += 3) {
  84967. faceAdjacencies = new FaceAdjacencies();
  84968. var p0Index = indices[index];
  84969. var p1Index = indices[index + 1];
  84970. var p2Index = indices[index + 2];
  84971. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  84972. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  84973. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  84974. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  84975. faceNormal.normalize();
  84976. faceNormals.push(faceNormal);
  84977. adjacencies.push(faceAdjacencies);
  84978. }
  84979. // Scan
  84980. for (index = 0; index < adjacencies.length; index++) {
  84981. faceAdjacencies = adjacencies[index];
  84982. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  84983. var otherFaceAdjacencies = adjacencies[otherIndex];
  84984. if (faceAdjacencies.edgesConnectedCount === 3) {
  84985. break;
  84986. }
  84987. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  84988. continue;
  84989. }
  84990. var otherP0 = indices[otherIndex * 3];
  84991. var otherP1 = indices[otherIndex * 3 + 1];
  84992. var otherP2 = indices[otherIndex * 3 + 2];
  84993. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  84994. var otherEdgeIndex = 0;
  84995. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  84996. continue;
  84997. }
  84998. switch (edgeIndex) {
  84999. case 0:
  85000. if (this._checkVerticesInsteadOfIndices) {
  85001. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85002. }
  85003. else {
  85004. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  85005. }
  85006. break;
  85007. case 1:
  85008. if (this._checkVerticesInsteadOfIndices) {
  85009. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85010. }
  85011. else {
  85012. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  85013. }
  85014. break;
  85015. case 2:
  85016. if (this._checkVerticesInsteadOfIndices) {
  85017. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85018. }
  85019. else {
  85020. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  85021. }
  85022. break;
  85023. }
  85024. if (otherEdgeIndex === -1) {
  85025. continue;
  85026. }
  85027. faceAdjacencies.edges[edgeIndex] = otherIndex;
  85028. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  85029. faceAdjacencies.edgesConnectedCount++;
  85030. otherFaceAdjacencies.edgesConnectedCount++;
  85031. if (faceAdjacencies.edgesConnectedCount === 3) {
  85032. break;
  85033. }
  85034. }
  85035. }
  85036. }
  85037. // Create lines
  85038. for (index = 0; index < adjacencies.length; index++) {
  85039. // 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
  85040. var current = adjacencies[index];
  85041. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  85042. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  85043. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  85044. }
  85045. // Merge into a single mesh
  85046. var engine = this._source.getScene().getEngine();
  85047. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  85048. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  85049. this._ib = engine.createIndexBuffer(this._linesIndices);
  85050. this._indicesCount = this._linesIndices.length;
  85051. };
  85052. EdgesRenderer.prototype.render = function () {
  85053. var scene = this._source.getScene();
  85054. if (!this._lineShader.isReady() || !scene.activeCamera) {
  85055. return;
  85056. }
  85057. var engine = scene.getEngine();
  85058. this._lineShader._preBind();
  85059. // VBOs
  85060. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  85061. scene.resetCachedMaterial();
  85062. this._lineShader.setColor4("color", this._source.edgesColor);
  85063. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  85064. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  85065. }
  85066. else {
  85067. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  85068. }
  85069. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  85070. this._lineShader.bind(this._source.getWorldMatrix());
  85071. // Draw order
  85072. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  85073. this._lineShader.unbind();
  85074. engine.setDepthWrite(true);
  85075. };
  85076. return EdgesRenderer;
  85077. }());
  85078. BABYLON.EdgesRenderer = EdgesRenderer;
  85079. })(BABYLON || (BABYLON = {}));
  85080. //# sourceMappingURL=babylon.edgesRenderer.js.map
  85081. var __assign = (this && this.__assign) || Object.assign || function(t) {
  85082. for (var s, i = 1, n = arguments.length; i < n; i++) {
  85083. s = arguments[i];
  85084. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  85085. t[p] = s[p];
  85086. }
  85087. return t;
  85088. };
  85089. var BABYLON;
  85090. (function (BABYLON) {
  85091. /**
  85092. * The effect layer Helps adding post process effect blended with the main pass.
  85093. *
  85094. * This can be for instance use to generate glow or higlight effects on the scene.
  85095. *
  85096. * The effect layer class can not be used directly and is intented to inherited from to be
  85097. * customized per effects.
  85098. */
  85099. var EffectLayer = /** @class */ (function () {
  85100. /**
  85101. * Instantiates a new effect Layer and references it in the scene.
  85102. * @param name The name of the layer
  85103. * @param scene The scene to use the layer in
  85104. */
  85105. function EffectLayer(
  85106. /** The Friendly of the effect in the scene */
  85107. name, scene) {
  85108. this.name = name;
  85109. this._vertexBuffers = {};
  85110. this._maxSize = 0;
  85111. this._mainTextureDesiredSize = { width: 0, height: 0 };
  85112. this._shouldRender = true;
  85113. this._postProcesses = [];
  85114. this._textures = [];
  85115. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  85116. /**
  85117. * The clear color of the texture used to generate the glow map.
  85118. */
  85119. this.neutralColor = new BABYLON.Color4();
  85120. /**
  85121. * Specifies wether the highlight layer is enabled or not.
  85122. */
  85123. this.isEnabled = true;
  85124. /**
  85125. * An event triggered when the effect layer has been disposed.
  85126. */
  85127. this.onDisposeObservable = new BABYLON.Observable();
  85128. /**
  85129. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  85130. */
  85131. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  85132. /**
  85133. * An event triggered when the generated texture is being merged in the scene.
  85134. */
  85135. this.onBeforeComposeObservable = new BABYLON.Observable();
  85136. /**
  85137. * An event triggered when the generated texture has been merged in the scene.
  85138. */
  85139. this.onAfterComposeObservable = new BABYLON.Observable();
  85140. /**
  85141. * An event triggered when the efffect layer changes its size.
  85142. */
  85143. this.onSizeChangedObservable = new BABYLON.Observable();
  85144. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85145. this._engine = scene.getEngine();
  85146. this._maxSize = this._engine.getCaps().maxTextureSize;
  85147. this._scene.effectLayers.push(this);
  85148. // Generate Buffers
  85149. this._generateIndexBuffer();
  85150. this._genrateVertexBuffer();
  85151. }
  85152. Object.defineProperty(EffectLayer.prototype, "camera", {
  85153. /**
  85154. * Gets the camera attached to the layer.
  85155. */
  85156. get: function () {
  85157. return this._effectLayerOptions.camera;
  85158. },
  85159. enumerable: true,
  85160. configurable: true
  85161. });
  85162. /**
  85163. * Initializes the effect layer with the required options.
  85164. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  85165. */
  85166. EffectLayer.prototype._init = function (options) {
  85167. // Adapt options
  85168. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85169. this._setMainTextureSize();
  85170. this._createMainTexture();
  85171. this._createTextureAndPostProcesses();
  85172. this._mergeEffect = this._createMergeEffect();
  85173. };
  85174. /**
  85175. * Generates the index buffer of the full screen quad blending to the main canvas.
  85176. */
  85177. EffectLayer.prototype._generateIndexBuffer = function () {
  85178. // Indices
  85179. var indices = [];
  85180. indices.push(0);
  85181. indices.push(1);
  85182. indices.push(2);
  85183. indices.push(0);
  85184. indices.push(2);
  85185. indices.push(3);
  85186. this._indexBuffer = this._engine.createIndexBuffer(indices);
  85187. };
  85188. /**
  85189. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  85190. */
  85191. EffectLayer.prototype._genrateVertexBuffer = function () {
  85192. // VBO
  85193. var vertices = [];
  85194. vertices.push(1, 1);
  85195. vertices.push(-1, 1);
  85196. vertices.push(-1, -1);
  85197. vertices.push(1, -1);
  85198. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85199. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  85200. };
  85201. /**
  85202. * Sets the main texture desired size which is the closest power of two
  85203. * of the engine canvas size.
  85204. */
  85205. EffectLayer.prototype._setMainTextureSize = function () {
  85206. if (this._effectLayerOptions.mainTextureFixedSize) {
  85207. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  85208. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  85209. }
  85210. else {
  85211. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  85212. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  85213. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  85214. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  85215. }
  85216. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  85217. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  85218. };
  85219. /**
  85220. * Creates the main texture for the effect layer.
  85221. */
  85222. EffectLayer.prototype._createMainTexture = function () {
  85223. var _this = this;
  85224. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  85225. width: this._mainTextureDesiredSize.width,
  85226. height: this._mainTextureDesiredSize.height
  85227. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85228. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  85229. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85230. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85231. this._mainTexture.anisotropicFilteringLevel = 1;
  85232. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85233. this._mainTexture.renderParticles = false;
  85234. this._mainTexture.renderList = null;
  85235. this._mainTexture.ignoreCameraViewport = true;
  85236. // Custom render function
  85237. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85238. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  85239. var index;
  85240. var engine = _this._scene.getEngine();
  85241. if (depthOnlySubMeshes.length) {
  85242. engine.setColorWrite(false);
  85243. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85244. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  85245. }
  85246. engine.setColorWrite(true);
  85247. }
  85248. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85249. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  85250. }
  85251. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85252. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  85253. }
  85254. for (index = 0; index < transparentSubMeshes.length; index++) {
  85255. _this._renderSubMesh(transparentSubMeshes.data[index]);
  85256. }
  85257. };
  85258. this._mainTexture.onClearObservable.add(function (engine) {
  85259. engine.clear(_this.neutralColor, true, true, true);
  85260. });
  85261. };
  85262. /**
  85263. * Checks for the readiness of the element composing the layer.
  85264. * @param subMesh the mesh to check for
  85265. * @param useInstances specify wether or not to use instances to render the mesh
  85266. * @param emissiveTexture the associated emissive texture used to generate the glow
  85267. * @return true if ready otherwise, false
  85268. */
  85269. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  85270. var material = subMesh.getMaterial();
  85271. if (!material) {
  85272. return false;
  85273. }
  85274. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  85275. return false;
  85276. }
  85277. var defines = [];
  85278. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85279. var mesh = subMesh.getMesh();
  85280. var uv1 = false;
  85281. var uv2 = false;
  85282. // Alpha test
  85283. if (material && material.needAlphaTesting()) {
  85284. var alphaTexture = material.getAlphaTestTexture();
  85285. if (alphaTexture) {
  85286. defines.push("#define ALPHATEST");
  85287. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85288. alphaTexture.coordinatesIndex === 1) {
  85289. defines.push("#define DIFFUSEUV2");
  85290. uv2 = true;
  85291. }
  85292. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85293. defines.push("#define DIFFUSEUV1");
  85294. uv1 = true;
  85295. }
  85296. }
  85297. }
  85298. // Emissive
  85299. if (emissiveTexture) {
  85300. defines.push("#define EMISSIVE");
  85301. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85302. emissiveTexture.coordinatesIndex === 1) {
  85303. defines.push("#define EMISSIVEUV2");
  85304. uv2 = true;
  85305. }
  85306. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85307. defines.push("#define EMISSIVEUV1");
  85308. uv1 = true;
  85309. }
  85310. }
  85311. if (uv1) {
  85312. attribs.push(BABYLON.VertexBuffer.UVKind);
  85313. defines.push("#define UV1");
  85314. }
  85315. if (uv2) {
  85316. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85317. defines.push("#define UV2");
  85318. }
  85319. // Bones
  85320. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85321. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85322. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85323. if (mesh.numBoneInfluencers > 4) {
  85324. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85325. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85326. }
  85327. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85328. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  85329. }
  85330. else {
  85331. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85332. }
  85333. // Instances
  85334. if (useInstances) {
  85335. defines.push("#define INSTANCES");
  85336. attribs.push("world0");
  85337. attribs.push("world1");
  85338. attribs.push("world2");
  85339. attribs.push("world3");
  85340. }
  85341. // Get correct effect
  85342. var join = defines.join("\n");
  85343. if (this._cachedDefines !== join) {
  85344. this._cachedDefines = join;
  85345. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  85346. }
  85347. return this._effectLayerMapGenerationEffect.isReady();
  85348. };
  85349. /**
  85350. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  85351. */
  85352. EffectLayer.prototype.render = function () {
  85353. var currentEffect = this._mergeEffect;
  85354. // Check
  85355. if (!currentEffect.isReady())
  85356. return;
  85357. for (var i = 0; i < this._postProcesses.length; i++) {
  85358. if (!this._postProcesses[i].isReady()) {
  85359. return;
  85360. }
  85361. }
  85362. var engine = this._scene.getEngine();
  85363. this.onBeforeComposeObservable.notifyObservers(this);
  85364. // Render
  85365. engine.enableEffect(currentEffect);
  85366. engine.setState(false);
  85367. // VBOs
  85368. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85369. // Cache
  85370. var previousAlphaMode = engine.getAlphaMode();
  85371. // Go Blend.
  85372. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  85373. // Blends the map on the main canvas.
  85374. this._internalRender(currentEffect);
  85375. // Restore Alpha
  85376. engine.setAlphaMode(previousAlphaMode);
  85377. this.onAfterComposeObservable.notifyObservers(this);
  85378. // Handle size changes.
  85379. var size = this._mainTexture.getSize();
  85380. this._setMainTextureSize();
  85381. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  85382. // Recreate RTT and post processes on size change.
  85383. this.onSizeChangedObservable.notifyObservers(this);
  85384. this._disposeTextureAndPostProcesses();
  85385. this._createMainTexture();
  85386. this._createTextureAndPostProcesses();
  85387. }
  85388. };
  85389. /**
  85390. * Determine if a given mesh will be used in the current effect.
  85391. * @param mesh mesh to test
  85392. * @returns true if the mesh will be used
  85393. */
  85394. EffectLayer.prototype.hasMesh = function (mesh) {
  85395. return true;
  85396. };
  85397. /**
  85398. * Returns true if the layer contains information to display, otherwise false.
  85399. * @returns true if the glow layer should be rendered
  85400. */
  85401. EffectLayer.prototype.shouldRender = function () {
  85402. return this.isEnabled && this._shouldRender;
  85403. };
  85404. /**
  85405. * Returns true if the mesh should render, otherwise false.
  85406. * @param mesh The mesh to render
  85407. * @returns true if it should render otherwise false
  85408. */
  85409. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  85410. return true;
  85411. };
  85412. /**
  85413. * Returns true if the mesh should render, otherwise false.
  85414. * @param mesh The mesh to render
  85415. * @returns true if it should render otherwise false
  85416. */
  85417. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  85418. return true;
  85419. };
  85420. /**
  85421. * Renders the submesh passed in parameter to the generation map.
  85422. */
  85423. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  85424. var _this = this;
  85425. if (!this.shouldRender()) {
  85426. return;
  85427. }
  85428. var material = subMesh.getMaterial();
  85429. var mesh = subMesh.getRenderingMesh();
  85430. var scene = this._scene;
  85431. var engine = scene.getEngine();
  85432. if (!material) {
  85433. return;
  85434. }
  85435. // Do not block in blend mode.
  85436. if (material.needAlphaBlendingForMesh(mesh)) {
  85437. return;
  85438. }
  85439. // Culling
  85440. engine.setState(material.backFaceCulling);
  85441. // Managing instances
  85442. var batch = mesh._getInstancesRenderList(subMesh._id);
  85443. if (batch.mustReturn) {
  85444. return;
  85445. }
  85446. // Early Exit per mesh
  85447. if (!this._shouldRenderMesh(mesh)) {
  85448. return;
  85449. }
  85450. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85451. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  85452. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  85453. engine.enableEffect(this._effectLayerMapGenerationEffect);
  85454. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  85455. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  85456. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  85457. // Alpha test
  85458. if (material && material.needAlphaTesting()) {
  85459. var alphaTexture = material.getAlphaTestTexture();
  85460. if (alphaTexture) {
  85461. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  85462. var textureMatrix = alphaTexture.getTextureMatrix();
  85463. if (textureMatrix) {
  85464. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  85465. }
  85466. }
  85467. }
  85468. // Glow emissive only
  85469. if (this._emissiveTextureAndColor.texture) {
  85470. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  85471. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  85472. }
  85473. // Bones
  85474. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85475. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85476. }
  85477. // Draw
  85478. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  85479. }
  85480. else {
  85481. // Need to reset refresh rate of the shadowMap
  85482. this._mainTexture.resetRefreshCounter();
  85483. }
  85484. };
  85485. /**
  85486. * Rebuild the required buffers.
  85487. * @ignore Internal use only.
  85488. */
  85489. EffectLayer.prototype._rebuild = function () {
  85490. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85491. if (vb) {
  85492. vb._rebuild();
  85493. }
  85494. this._generateIndexBuffer();
  85495. };
  85496. /**
  85497. * Dispose only the render target textures and post process.
  85498. */
  85499. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  85500. this._mainTexture.dispose();
  85501. for (var i = 0; i < this._postProcesses.length; i++) {
  85502. if (this._postProcesses[i]) {
  85503. this._postProcesses[i].dispose();
  85504. }
  85505. }
  85506. this._postProcesses = [];
  85507. for (var i = 0; i < this._textures.length; i++) {
  85508. if (this._textures[i]) {
  85509. this._textures[i].dispose();
  85510. }
  85511. }
  85512. this._textures = [];
  85513. };
  85514. /**
  85515. * Dispose the highlight layer and free resources.
  85516. */
  85517. EffectLayer.prototype.dispose = function () {
  85518. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85519. if (vertexBuffer) {
  85520. vertexBuffer.dispose();
  85521. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85522. }
  85523. if (this._indexBuffer) {
  85524. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85525. this._indexBuffer = null;
  85526. }
  85527. // Clean textures and post processes
  85528. this._disposeTextureAndPostProcesses();
  85529. // Remove from scene
  85530. var index = this._scene.effectLayers.indexOf(this, 0);
  85531. if (index > -1) {
  85532. this._scene.effectLayers.splice(index, 1);
  85533. }
  85534. // Callback
  85535. this.onDisposeObservable.notifyObservers(this);
  85536. this.onDisposeObservable.clear();
  85537. this.onBeforeRenderMainTextureObservable.clear();
  85538. this.onBeforeComposeObservable.clear();
  85539. this.onAfterComposeObservable.clear();
  85540. this.onSizeChangedObservable.clear();
  85541. };
  85542. return EffectLayer;
  85543. }());
  85544. BABYLON.EffectLayer = EffectLayer;
  85545. })(BABYLON || (BABYLON = {}));
  85546. //# sourceMappingURL=babylon.effectLayer.js.map
  85547. var BABYLON;
  85548. (function (BABYLON) {
  85549. /**
  85550. * Special Glow Blur post process only blurring the alpha channel
  85551. * It enforces keeping the most luminous color in the color channel.
  85552. */
  85553. var GlowBlurPostProcess = /** @class */ (function (_super) {
  85554. __extends(GlowBlurPostProcess, _super);
  85555. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  85556. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85557. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  85558. _this.direction = direction;
  85559. _this.kernel = kernel;
  85560. _this.onApplyObservable.add(function (effect) {
  85561. effect.setFloat2("screenSize", _this.width, _this.height);
  85562. effect.setVector2("direction", _this.direction);
  85563. effect.setFloat("blurWidth", _this.kernel);
  85564. });
  85565. return _this;
  85566. }
  85567. return GlowBlurPostProcess;
  85568. }(BABYLON.PostProcess));
  85569. /**
  85570. * The highlight layer Helps adding a glow effect around a mesh.
  85571. *
  85572. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85573. * glowy meshes to your scene.
  85574. *
  85575. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  85576. */
  85577. var HighlightLayer = /** @class */ (function (_super) {
  85578. __extends(HighlightLayer, _super);
  85579. /**
  85580. * Instantiates a new highlight Layer and references it to the scene..
  85581. * @param name The name of the layer
  85582. * @param scene The scene to use the layer in
  85583. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  85584. */
  85585. function HighlightLayer(name, scene, options) {
  85586. var _this = _super.call(this, name, scene) || this;
  85587. _this.name = name;
  85588. /**
  85589. * Specifies whether or not the inner glow is ACTIVE in the layer.
  85590. */
  85591. _this.innerGlow = true;
  85592. /**
  85593. * Specifies whether or not the outer glow is ACTIVE in the layer.
  85594. */
  85595. _this.outerGlow = true;
  85596. /**
  85597. * An event triggered when the highlight layer is being blurred.
  85598. */
  85599. _this.onBeforeBlurObservable = new BABYLON.Observable();
  85600. /**
  85601. * An event triggered when the highlight layer has been blurred.
  85602. */
  85603. _this.onAfterBlurObservable = new BABYLON.Observable();
  85604. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  85605. _this._meshes = {};
  85606. _this._excludedMeshes = {};
  85607. _this.neutralColor = HighlightLayer.NeutralColor;
  85608. // Warn on stencil
  85609. if (!_this._engine.isStencilEnable) {
  85610. 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 }");
  85611. }
  85612. // Adapt options
  85613. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85614. // Initialize the layer
  85615. _this._init({
  85616. alphaBlendingMode: _this._options.alphaBlendingMode,
  85617. camera: _this._options.camera,
  85618. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85619. mainTextureRatio: _this._options.mainTextureRatio
  85620. });
  85621. // Do not render as long as no meshes have been added
  85622. _this._shouldRender = false;
  85623. return _this;
  85624. }
  85625. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  85626. /**
  85627. * Gets the horizontal size of the blur.
  85628. */
  85629. get: function () {
  85630. return this._horizontalBlurPostprocess.kernel;
  85631. },
  85632. /**
  85633. * Specifies the horizontal size of the blur.
  85634. */
  85635. set: function (value) {
  85636. this._horizontalBlurPostprocess.kernel = value;
  85637. },
  85638. enumerable: true,
  85639. configurable: true
  85640. });
  85641. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  85642. /**
  85643. * Gets the vertical size of the blur.
  85644. */
  85645. get: function () {
  85646. return this._verticalBlurPostprocess.kernel;
  85647. },
  85648. /**
  85649. * Specifies the vertical size of the blur.
  85650. */
  85651. set: function (value) {
  85652. this._verticalBlurPostprocess.kernel = value;
  85653. },
  85654. enumerable: true,
  85655. configurable: true
  85656. });
  85657. /**
  85658. * Get the effect name of the layer.
  85659. * @return The effect name
  85660. */
  85661. HighlightLayer.prototype.getEffectName = function () {
  85662. return HighlightLayer.EffectName;
  85663. };
  85664. /**
  85665. * Create the merge effect. This is the shader use to blit the information back
  85666. * to the main canvas at the end of the scene rendering.
  85667. */
  85668. HighlightLayer.prototype._createMergeEffect = function () {
  85669. // Effect
  85670. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  85671. };
  85672. /**
  85673. * Creates the render target textures and post processes used in the highlight layer.
  85674. */
  85675. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  85676. var _this = this;
  85677. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  85678. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  85679. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85680. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85681. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  85682. width: blurTextureWidth,
  85683. height: blurTextureHeight
  85684. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85685. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85686. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85687. this._blurTexture.anisotropicFilteringLevel = 16;
  85688. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85689. this._blurTexture.renderParticles = false;
  85690. this._blurTexture.ignoreCameraViewport = true;
  85691. this._textures = [this._blurTexture];
  85692. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  85693. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85694. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  85695. effect.setTexture("textureSampler", _this._mainTexture);
  85696. });
  85697. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85698. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85699. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85700. });
  85701. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85702. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  85703. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85704. });
  85705. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85706. }
  85707. else {
  85708. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  85709. width: blurTextureWidth,
  85710. height: blurTextureHeight
  85711. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85712. this._horizontalBlurPostprocess.width = blurTextureWidth;
  85713. this._horizontalBlurPostprocess.height = blurTextureHeight;
  85714. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85715. effect.setTexture("textureSampler", _this._mainTexture);
  85716. });
  85717. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  85718. width: blurTextureWidth,
  85719. height: blurTextureHeight
  85720. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85721. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85722. }
  85723. this._mainTexture.onAfterUnbindObservable.add(function () {
  85724. _this.onBeforeBlurObservable.notifyObservers(_this);
  85725. var internalTexture = _this._blurTexture.getInternalTexture();
  85726. if (internalTexture) {
  85727. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  85728. }
  85729. _this.onAfterBlurObservable.notifyObservers(_this);
  85730. });
  85731. // Prevent autoClear.
  85732. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85733. };
  85734. /**
  85735. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85736. */
  85737. HighlightLayer.prototype.needStencil = function () {
  85738. return true;
  85739. };
  85740. /**
  85741. * Checks for the readiness of the element composing the layer.
  85742. * @param subMesh the mesh to check for
  85743. * @param useInstances specify wether or not to use instances to render the mesh
  85744. * @param emissiveTexture the associated emissive texture used to generate the glow
  85745. * @return true if ready otherwise, false
  85746. */
  85747. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  85748. var material = subMesh.getMaterial();
  85749. var mesh = subMesh.getRenderingMesh();
  85750. if (!material || !mesh || !this._meshes) {
  85751. return false;
  85752. }
  85753. var emissiveTexture = null;
  85754. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85755. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85756. emissiveTexture = material.emissiveTexture;
  85757. }
  85758. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85759. };
  85760. /**
  85761. * Implementation specific of rendering the generating effect on the main canvas.
  85762. * @param effect The effect used to render through
  85763. */
  85764. HighlightLayer.prototype._internalRender = function (effect) {
  85765. // Texture
  85766. effect.setTexture("textureSampler", this._blurTexture);
  85767. // Cache
  85768. var engine = this._engine;
  85769. var previousStencilBuffer = engine.getStencilBuffer();
  85770. var previousStencilFunction = engine.getStencilFunction();
  85771. var previousStencilMask = engine.getStencilMask();
  85772. var previousStencilOperationPass = engine.getStencilOperationPass();
  85773. var previousStencilOperationFail = engine.getStencilOperationFail();
  85774. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  85775. var previousStencilReference = engine.getStencilFunctionReference();
  85776. // Stencil operations
  85777. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  85778. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  85779. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  85780. // Draw order
  85781. engine.setStencilMask(0x00);
  85782. engine.setStencilBuffer(true);
  85783. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  85784. // 2 passes inner outer
  85785. if (this.outerGlow) {
  85786. effect.setFloat("offset", 0);
  85787. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  85788. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85789. }
  85790. if (this.innerGlow) {
  85791. effect.setFloat("offset", 1);
  85792. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  85793. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85794. }
  85795. // Restore Cache
  85796. engine.setStencilFunction(previousStencilFunction);
  85797. engine.setStencilMask(previousStencilMask);
  85798. engine.setStencilBuffer(previousStencilBuffer);
  85799. engine.setStencilOperationPass(previousStencilOperationPass);
  85800. engine.setStencilOperationFail(previousStencilOperationFail);
  85801. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  85802. engine.setStencilFunctionReference(previousStencilReference);
  85803. };
  85804. /**
  85805. * Returns true if the layer contains information to display, otherwise false.
  85806. */
  85807. HighlightLayer.prototype.shouldRender = function () {
  85808. if (_super.prototype.shouldRender.call(this)) {
  85809. return this._meshes ? true : false;
  85810. }
  85811. return false;
  85812. };
  85813. /**
  85814. * Returns true if the mesh should render, otherwise false.
  85815. * @param mesh The mesh to render
  85816. * @returns true if it should render otherwise false
  85817. */
  85818. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  85819. // Excluded Mesh
  85820. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  85821. return false;
  85822. }
  85823. ;
  85824. return true;
  85825. };
  85826. /**
  85827. * Sets the required values for both the emissive texture and and the main color.
  85828. */
  85829. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85830. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85831. if (highlightLayerMesh) {
  85832. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  85833. }
  85834. else {
  85835. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85836. }
  85837. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85838. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85839. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  85840. }
  85841. else {
  85842. this._emissiveTextureAndColor.texture = null;
  85843. }
  85844. };
  85845. /**
  85846. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  85847. * @param mesh The mesh to exclude from the highlight layer
  85848. */
  85849. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  85850. if (!this._excludedMeshes) {
  85851. return;
  85852. }
  85853. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85854. if (!meshExcluded) {
  85855. this._excludedMeshes[mesh.uniqueId] = {
  85856. mesh: mesh,
  85857. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  85858. mesh.getEngine().setStencilBuffer(false);
  85859. }),
  85860. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  85861. mesh.getEngine().setStencilBuffer(true);
  85862. }),
  85863. };
  85864. }
  85865. };
  85866. /**
  85867. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  85868. * @param mesh The mesh to highlight
  85869. */
  85870. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  85871. if (!this._excludedMeshes) {
  85872. return;
  85873. }
  85874. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85875. if (meshExcluded) {
  85876. if (meshExcluded.beforeRender) {
  85877. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  85878. }
  85879. if (meshExcluded.afterRender) {
  85880. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  85881. }
  85882. }
  85883. this._excludedMeshes[mesh.uniqueId] = null;
  85884. };
  85885. /**
  85886. * Determine if a given mesh will be highlighted by the current HighlightLayer
  85887. * @param mesh mesh to test
  85888. * @returns true if the mesh will be highlighted by the current HighlightLayer
  85889. */
  85890. HighlightLayer.prototype.hasMesh = function (mesh) {
  85891. if (!this._meshes) {
  85892. return false;
  85893. }
  85894. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  85895. };
  85896. /**
  85897. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  85898. * @param mesh The mesh to highlight
  85899. * @param color The color of the highlight
  85900. * @param glowEmissiveOnly Extract the glow from the emissive texture
  85901. */
  85902. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  85903. var _this = this;
  85904. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  85905. if (!this._meshes) {
  85906. return;
  85907. }
  85908. var meshHighlight = this._meshes[mesh.uniqueId];
  85909. if (meshHighlight) {
  85910. meshHighlight.color = color;
  85911. }
  85912. else {
  85913. this._meshes[mesh.uniqueId] = {
  85914. mesh: mesh,
  85915. color: color,
  85916. // Lambda required for capture due to Observable this context
  85917. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  85918. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  85919. _this._defaultStencilReference(mesh);
  85920. }
  85921. else {
  85922. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  85923. }
  85924. }),
  85925. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  85926. glowEmissiveOnly: glowEmissiveOnly
  85927. };
  85928. }
  85929. this._shouldRender = true;
  85930. };
  85931. /**
  85932. * Remove a mesh from the highlight layer in order to make it stop glowing.
  85933. * @param mesh The mesh to highlight
  85934. */
  85935. HighlightLayer.prototype.removeMesh = function (mesh) {
  85936. if (!this._meshes) {
  85937. return;
  85938. }
  85939. var meshHighlight = this._meshes[mesh.uniqueId];
  85940. if (meshHighlight) {
  85941. if (meshHighlight.observerHighlight) {
  85942. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85943. }
  85944. if (meshHighlight.observerDefault) {
  85945. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85946. }
  85947. delete this._meshes[mesh.uniqueId];
  85948. }
  85949. this._shouldRender = false;
  85950. for (var meshHighlightToCheck in this._meshes) {
  85951. if (this._meshes[meshHighlightToCheck]) {
  85952. this._shouldRender = true;
  85953. break;
  85954. }
  85955. }
  85956. };
  85957. /**
  85958. * Force the stencil to the normal expected value for none glowing parts
  85959. */
  85960. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  85961. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  85962. };
  85963. /**
  85964. * Free any resources and references associated to a mesh.
  85965. * Internal use
  85966. * @param mesh The mesh to free.
  85967. */
  85968. HighlightLayer.prototype._disposeMesh = function (mesh) {
  85969. this.removeMesh(mesh);
  85970. this.removeExcludedMesh(mesh);
  85971. };
  85972. /**
  85973. * Dispose the highlight layer and free resources.
  85974. */
  85975. HighlightLayer.prototype.dispose = function () {
  85976. if (this._meshes) {
  85977. // Clean mesh references
  85978. for (var id in this._meshes) {
  85979. var meshHighlight = this._meshes[id];
  85980. if (meshHighlight && meshHighlight.mesh) {
  85981. if (meshHighlight.observerHighlight) {
  85982. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85983. }
  85984. if (meshHighlight.observerDefault) {
  85985. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85986. }
  85987. }
  85988. }
  85989. this._meshes = null;
  85990. }
  85991. if (this._excludedMeshes) {
  85992. for (var id in this._excludedMeshes) {
  85993. var meshHighlight = this._excludedMeshes[id];
  85994. if (meshHighlight) {
  85995. if (meshHighlight.beforeRender) {
  85996. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  85997. }
  85998. if (meshHighlight.afterRender) {
  85999. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  86000. }
  86001. }
  86002. }
  86003. this._excludedMeshes = null;
  86004. }
  86005. _super.prototype.dispose.call(this);
  86006. };
  86007. /**
  86008. * Effect Name of the highlight layer.
  86009. */
  86010. HighlightLayer.EffectName = "HighlightLayer";
  86011. /**
  86012. * The neutral color used during the preparation of the glow effect.
  86013. * This is black by default as the blend operation is a blend operation.
  86014. */
  86015. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  86016. /**
  86017. * Stencil value used for glowing meshes.
  86018. */
  86019. HighlightLayer.GlowingMeshStencilReference = 0x02;
  86020. /**
  86021. * Stencil value used for the other meshes in the scene.
  86022. */
  86023. HighlightLayer.NormalMeshStencilReference = 0x01;
  86024. return HighlightLayer;
  86025. }(BABYLON.EffectLayer));
  86026. BABYLON.HighlightLayer = HighlightLayer;
  86027. })(BABYLON || (BABYLON = {}));
  86028. //# sourceMappingURL=babylon.highlightLayer.js.map
  86029. var BABYLON;
  86030. (function (BABYLON) {
  86031. /**
  86032. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  86033. *
  86034. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86035. * glowy meshes to your scene.
  86036. *
  86037. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  86038. */
  86039. var GlowLayer = /** @class */ (function (_super) {
  86040. __extends(GlowLayer, _super);
  86041. /**
  86042. * Instantiates a new glow Layer and references it to the scene.
  86043. * @param name The name of the layer
  86044. * @param scene The scene to use the layer in
  86045. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  86046. */
  86047. function GlowLayer(name, scene, options) {
  86048. var _this = _super.call(this, name, scene) || this;
  86049. _this.name = name;
  86050. _this._intensity = 1.0;
  86051. _this._includedOnlyMeshes = [];
  86052. _this._excludedMeshes = [];
  86053. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  86054. // Adapt options
  86055. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  86056. // Initialize the layer
  86057. _this._init({
  86058. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  86059. camera: _this._options.camera,
  86060. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86061. mainTextureRatio: _this._options.mainTextureRatio
  86062. });
  86063. return _this;
  86064. }
  86065. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  86066. /**
  86067. * Gets the kernel size of the blur.
  86068. */
  86069. get: function () {
  86070. return this._horizontalBlurPostprocess1.kernel;
  86071. },
  86072. /**
  86073. * Sets the kernel size of the blur.
  86074. */
  86075. set: function (value) {
  86076. this._horizontalBlurPostprocess1.kernel = value;
  86077. this._verticalBlurPostprocess1.kernel = value;
  86078. this._horizontalBlurPostprocess2.kernel = value;
  86079. this._verticalBlurPostprocess2.kernel = value;
  86080. },
  86081. enumerable: true,
  86082. configurable: true
  86083. });
  86084. Object.defineProperty(GlowLayer.prototype, "intensity", {
  86085. /**
  86086. * Gets the glow intensity.
  86087. */
  86088. get: function () {
  86089. return this._intensity;
  86090. },
  86091. /**
  86092. * Sets the glow intensity.
  86093. */
  86094. set: function (value) {
  86095. this._intensity = value;
  86096. },
  86097. enumerable: true,
  86098. configurable: true
  86099. });
  86100. /**
  86101. * Get the effect name of the layer.
  86102. * @return The effect name
  86103. */
  86104. GlowLayer.prototype.getEffectName = function () {
  86105. return GlowLayer.EffectName;
  86106. };
  86107. /**
  86108. * Create the merge effect. This is the shader use to blit the information back
  86109. * to the main canvas at the end of the scene rendering.
  86110. */
  86111. GlowLayer.prototype._createMergeEffect = function () {
  86112. // Effect
  86113. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  86114. };
  86115. /**
  86116. * Creates the render target textures and post processes used in the glow layer.
  86117. */
  86118. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  86119. var _this = this;
  86120. var blurTextureWidth = this._mainTextureDesiredSize.width;
  86121. var blurTextureHeight = this._mainTextureDesiredSize.height;
  86122. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86123. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86124. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  86125. width: blurTextureWidth,
  86126. height: blurTextureHeight
  86127. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86128. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86129. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86130. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86131. this._blurTexture1.renderParticles = false;
  86132. this._blurTexture1.ignoreCameraViewport = true;
  86133. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  86134. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  86135. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  86136. width: blurTextureWidth2,
  86137. height: blurTextureHeight2
  86138. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86139. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86140. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86141. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86142. this._blurTexture2.renderParticles = false;
  86143. this._blurTexture2.ignoreCameraViewport = true;
  86144. this._textures = [this._blurTexture1, this._blurTexture2];
  86145. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86146. width: blurTextureWidth,
  86147. height: blurTextureHeight
  86148. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86149. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  86150. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  86151. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  86152. effect.setTexture("textureSampler", _this._mainTexture);
  86153. });
  86154. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86155. width: blurTextureWidth,
  86156. height: blurTextureHeight
  86157. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86158. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86159. width: blurTextureWidth2,
  86160. height: blurTextureHeight2
  86161. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86162. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  86163. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  86164. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  86165. effect.setTexture("textureSampler", _this._blurTexture1);
  86166. });
  86167. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86168. width: blurTextureWidth2,
  86169. height: blurTextureHeight2
  86170. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86171. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86172. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  86173. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86174. this._mainTexture.samples = this._options.mainTextureSamples;
  86175. this._mainTexture.onAfterUnbindObservable.add(function () {
  86176. var internalTexture = _this._blurTexture1.getInternalTexture();
  86177. if (internalTexture) {
  86178. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  86179. internalTexture = _this._blurTexture2.getInternalTexture();
  86180. if (internalTexture) {
  86181. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  86182. }
  86183. }
  86184. });
  86185. // Prevent autoClear.
  86186. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86187. };
  86188. /**
  86189. * Checks for the readiness of the element composing the layer.
  86190. * @param subMesh the mesh to check for
  86191. * @param useInstances specify wether or not to use instances to render the mesh
  86192. * @param emissiveTexture the associated emissive texture used to generate the glow
  86193. * @return true if ready otherwise, false
  86194. */
  86195. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  86196. var material = subMesh.getMaterial();
  86197. var mesh = subMesh.getRenderingMesh();
  86198. if (!material || !mesh) {
  86199. return false;
  86200. }
  86201. var emissiveTexture = material.emissiveTexture;
  86202. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86203. };
  86204. /**
  86205. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86206. */
  86207. GlowLayer.prototype.needStencil = function () {
  86208. return false;
  86209. };
  86210. /**
  86211. * Implementation specific of rendering the generating effect on the main canvas.
  86212. * @param effect The effect used to render through
  86213. */
  86214. GlowLayer.prototype._internalRender = function (effect) {
  86215. // Texture
  86216. effect.setTexture("textureSampler", this._blurTexture1);
  86217. effect.setTexture("textureSampler2", this._blurTexture2);
  86218. effect.setFloat("offset", this._intensity);
  86219. // Cache
  86220. var engine = this._engine;
  86221. var previousStencilBuffer = engine.getStencilBuffer();
  86222. // Draw order
  86223. engine.setStencilBuffer(false);
  86224. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86225. // Draw order
  86226. engine.setStencilBuffer(previousStencilBuffer);
  86227. };
  86228. /**
  86229. * Sets the required values for both the emissive texture and and the main color.
  86230. */
  86231. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86232. var textureLevel = 1.0;
  86233. if (this.customEmissiveTextureSelector) {
  86234. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  86235. }
  86236. else {
  86237. if (material) {
  86238. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86239. if (this._emissiveTextureAndColor.texture) {
  86240. textureLevel = this._emissiveTextureAndColor.texture.level;
  86241. }
  86242. }
  86243. else {
  86244. this._emissiveTextureAndColor.texture = null;
  86245. }
  86246. }
  86247. if (this.customEmissiveColorSelector) {
  86248. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  86249. }
  86250. else {
  86251. if (material.emissiveColor) {
  86252. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  86253. }
  86254. else {
  86255. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86256. }
  86257. }
  86258. };
  86259. /**
  86260. * Returns true if the mesh should render, otherwise false.
  86261. * @param mesh The mesh to render
  86262. * @returns true if it should render otherwise false
  86263. */
  86264. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  86265. return this.hasMesh(mesh);
  86266. };
  86267. /**
  86268. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  86269. * @param mesh The mesh to exclude from the glow layer
  86270. */
  86271. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  86272. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  86273. this._excludedMeshes.push(mesh.uniqueId);
  86274. }
  86275. };
  86276. /**
  86277. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  86278. * @param mesh The mesh to remove
  86279. */
  86280. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  86281. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  86282. if (index !== -1) {
  86283. this._excludedMeshes.splice(index, 1);
  86284. }
  86285. };
  86286. /**
  86287. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  86288. * @param mesh The mesh to include in the glow layer
  86289. */
  86290. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  86291. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  86292. this._includedOnlyMeshes.push(mesh.uniqueId);
  86293. }
  86294. };
  86295. /**
  86296. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  86297. * @param mesh The mesh to remove
  86298. */
  86299. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  86300. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  86301. if (index !== -1) {
  86302. this._includedOnlyMeshes.splice(index, 1);
  86303. }
  86304. };
  86305. /**
  86306. * Determine if a given mesh will be used in the glow layer
  86307. * @param mesh The mesh to test
  86308. * @returns true if the mesh will be highlighted by the current glow layer
  86309. */
  86310. GlowLayer.prototype.hasMesh = function (mesh) {
  86311. // Included Mesh
  86312. if (this._includedOnlyMeshes.length) {
  86313. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  86314. }
  86315. ;
  86316. // Excluded Mesh
  86317. if (this._excludedMeshes.length) {
  86318. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  86319. }
  86320. ;
  86321. return true;
  86322. };
  86323. /**
  86324. * Free any resources and references associated to a mesh.
  86325. * Internal use
  86326. * @param mesh The mesh to free.
  86327. */
  86328. GlowLayer.prototype._disposeMesh = function (mesh) {
  86329. this.removeIncludedOnlyMesh(mesh);
  86330. this.removeExcludedMesh(mesh);
  86331. };
  86332. /**
  86333. * Effect Name of the layer.
  86334. */
  86335. GlowLayer.EffectName = "GlowLayer";
  86336. /**
  86337. * The default blur kernel size used for the glow.
  86338. */
  86339. GlowLayer.DefaultBlurKernelSize = 32;
  86340. /**
  86341. * The default texture size ratio used for the glow.
  86342. */
  86343. GlowLayer.DefaultTextureRatio = 0.5;
  86344. return GlowLayer;
  86345. }(BABYLON.EffectLayer));
  86346. BABYLON.GlowLayer = GlowLayer;
  86347. })(BABYLON || (BABYLON = {}));
  86348. //# sourceMappingURL=babylon.glowLayer.js.map
  86349. var BABYLON;
  86350. (function (BABYLON) {
  86351. /**
  86352. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  86353. */
  86354. var AssetTaskState;
  86355. (function (AssetTaskState) {
  86356. /**
  86357. * Initialization
  86358. */
  86359. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  86360. /**
  86361. * Running
  86362. */
  86363. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  86364. /**
  86365. * Done
  86366. */
  86367. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  86368. /**
  86369. * Error
  86370. */
  86371. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  86372. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  86373. /**
  86374. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  86375. */
  86376. var AbstractAssetTask = /** @class */ (function () {
  86377. /**
  86378. * Creates a new {BABYLON.AssetsManager}
  86379. * @param name defines the name of the task
  86380. */
  86381. function AbstractAssetTask(
  86382. /**
  86383. * Task name
  86384. */ name) {
  86385. this.name = name;
  86386. this._isCompleted = false;
  86387. this._taskState = AssetTaskState.INIT;
  86388. }
  86389. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  86390. /**
  86391. * Get if the task is completed
  86392. */
  86393. get: function () {
  86394. return this._isCompleted;
  86395. },
  86396. enumerable: true,
  86397. configurable: true
  86398. });
  86399. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  86400. /**
  86401. * Gets the current state of the task
  86402. */
  86403. get: function () {
  86404. return this._taskState;
  86405. },
  86406. enumerable: true,
  86407. configurable: true
  86408. });
  86409. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  86410. /**
  86411. * Gets the current error object (if task is in error)
  86412. */
  86413. get: function () {
  86414. return this._errorObject;
  86415. },
  86416. enumerable: true,
  86417. configurable: true
  86418. });
  86419. /**
  86420. * Internal only
  86421. * @ignore
  86422. */
  86423. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  86424. if (this._errorObject) {
  86425. return;
  86426. }
  86427. this._errorObject = {
  86428. message: message,
  86429. exception: exception
  86430. };
  86431. };
  86432. /**
  86433. * Execute the current task
  86434. * @param scene defines the scene where you want your assets to be loaded
  86435. * @param onSuccess is a callback called when the task is successfully executed
  86436. * @param onError is a callback called if an error occurs
  86437. */
  86438. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86439. var _this = this;
  86440. this._taskState = AssetTaskState.RUNNING;
  86441. this.runTask(scene, function () {
  86442. _this.onDoneCallback(onSuccess, onError);
  86443. }, function (msg, exception) {
  86444. _this.onErrorCallback(onError, msg, exception);
  86445. });
  86446. };
  86447. /**
  86448. * Execute the current task
  86449. * @param scene defines the scene where you want your assets to be loaded
  86450. * @param onSuccess is a callback called when the task is successfully executed
  86451. * @param onError is a callback called if an error occurs
  86452. */
  86453. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86454. throw new Error("runTask is not implemented");
  86455. };
  86456. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  86457. this._taskState = AssetTaskState.ERROR;
  86458. this._errorObject = {
  86459. message: message,
  86460. exception: exception
  86461. };
  86462. if (this.onError) {
  86463. this.onError(this, message, exception);
  86464. }
  86465. onError();
  86466. };
  86467. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  86468. try {
  86469. this._taskState = AssetTaskState.DONE;
  86470. this._isCompleted = true;
  86471. if (this.onSuccess) {
  86472. this.onSuccess(this);
  86473. }
  86474. onSuccess();
  86475. }
  86476. catch (e) {
  86477. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  86478. }
  86479. };
  86480. return AbstractAssetTask;
  86481. }());
  86482. BABYLON.AbstractAssetTask = AbstractAssetTask;
  86483. /**
  86484. * Class used to share progress information about assets loading
  86485. */
  86486. var AssetsProgressEvent = /** @class */ (function () {
  86487. /**
  86488. * Creates a {BABYLON.AssetsProgressEvent}
  86489. * @param remainingCount defines the number of remaining tasks to process
  86490. * @param totalCount defines the total number of tasks
  86491. * @param task defines the task that was just processed
  86492. */
  86493. function AssetsProgressEvent(remainingCount, totalCount, task) {
  86494. this.remainingCount = remainingCount;
  86495. this.totalCount = totalCount;
  86496. this.task = task;
  86497. }
  86498. return AssetsProgressEvent;
  86499. }());
  86500. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  86501. /**
  86502. * Define a task used by {BABYLON.AssetsManager} to load meshes
  86503. */
  86504. var MeshAssetTask = /** @class */ (function (_super) {
  86505. __extends(MeshAssetTask, _super);
  86506. /**
  86507. * Creates a new {BABYLON.MeshAssetTask}
  86508. * @param name defines the name of the task
  86509. * @param meshesNames defines the list of mesh's names you want to load
  86510. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  86511. * @param sceneFilename defines the filename of the scene to load from
  86512. */
  86513. function MeshAssetTask(
  86514. /**
  86515. * Defines the name of the task
  86516. */
  86517. name,
  86518. /**
  86519. * Defines the list of mesh's names you want to load
  86520. */
  86521. meshesNames,
  86522. /**
  86523. * Defines the root url to use as a base to load your meshes and associated resources
  86524. */
  86525. rootUrl,
  86526. /**
  86527. * Defines the filename of the scene to load from
  86528. */
  86529. sceneFilename) {
  86530. var _this = _super.call(this, name) || this;
  86531. _this.name = name;
  86532. _this.meshesNames = meshesNames;
  86533. _this.rootUrl = rootUrl;
  86534. _this.sceneFilename = sceneFilename;
  86535. return _this;
  86536. }
  86537. /**
  86538. * Execute the current task
  86539. * @param scene defines the scene where you want your assets to be loaded
  86540. * @param onSuccess is a callback called when the task is successfully executed
  86541. * @param onError is a callback called if an error occurs
  86542. */
  86543. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86544. var _this = this;
  86545. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  86546. _this.loadedMeshes = meshes;
  86547. _this.loadedParticleSystems = particleSystems;
  86548. _this.loadedSkeletons = skeletons;
  86549. onSuccess();
  86550. }, null, function (scene, message, exception) {
  86551. onError(message, exception);
  86552. });
  86553. };
  86554. return MeshAssetTask;
  86555. }(AbstractAssetTask));
  86556. BABYLON.MeshAssetTask = MeshAssetTask;
  86557. /**
  86558. * Define a task used by {BABYLON.AssetsManager} to load text content
  86559. */
  86560. var TextFileAssetTask = /** @class */ (function (_super) {
  86561. __extends(TextFileAssetTask, _super);
  86562. /**
  86563. * Creates a new TextFileAssetTask object
  86564. * @param name defines the name of the task
  86565. * @param url defines the location of the file to load
  86566. */
  86567. function TextFileAssetTask(
  86568. /**
  86569. * Defines the name of the task
  86570. */
  86571. name,
  86572. /**
  86573. * Defines the location of the file to load
  86574. */
  86575. url) {
  86576. var _this = _super.call(this, name) || this;
  86577. _this.name = name;
  86578. _this.url = url;
  86579. return _this;
  86580. }
  86581. /**
  86582. * Execute the current task
  86583. * @param scene defines the scene where you want your assets to be loaded
  86584. * @param onSuccess is a callback called when the task is successfully executed
  86585. * @param onError is a callback called if an error occurs
  86586. */
  86587. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86588. var _this = this;
  86589. scene._loadFile(this.url, function (data) {
  86590. _this.text = data;
  86591. onSuccess();
  86592. }, undefined, false, false, function (request, exception) {
  86593. if (request) {
  86594. onError(request.status + " " + request.statusText, exception);
  86595. }
  86596. });
  86597. };
  86598. return TextFileAssetTask;
  86599. }(AbstractAssetTask));
  86600. BABYLON.TextFileAssetTask = TextFileAssetTask;
  86601. /**
  86602. * Define a task used by {BABYLON.AssetsManager} to load binary data
  86603. */
  86604. var BinaryFileAssetTask = /** @class */ (function (_super) {
  86605. __extends(BinaryFileAssetTask, _super);
  86606. /**
  86607. * Creates a new BinaryFileAssetTask object
  86608. * @param name defines the name of the new task
  86609. * @param url defines the location of the file to load
  86610. */
  86611. function BinaryFileAssetTask(
  86612. /**
  86613. * Defines the name of the task
  86614. */
  86615. name,
  86616. /**
  86617. * Defines the location of the file to load
  86618. */
  86619. url) {
  86620. var _this = _super.call(this, name) || this;
  86621. _this.name = name;
  86622. _this.url = url;
  86623. return _this;
  86624. }
  86625. /**
  86626. * Execute the current task
  86627. * @param scene defines the scene where you want your assets to be loaded
  86628. * @param onSuccess is a callback called when the task is successfully executed
  86629. * @param onError is a callback called if an error occurs
  86630. */
  86631. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86632. var _this = this;
  86633. scene._loadFile(this.url, function (data) {
  86634. _this.data = data;
  86635. onSuccess();
  86636. }, undefined, true, true, function (request, exception) {
  86637. if (request) {
  86638. onError(request.status + " " + request.statusText, exception);
  86639. }
  86640. });
  86641. };
  86642. return BinaryFileAssetTask;
  86643. }(AbstractAssetTask));
  86644. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  86645. /**
  86646. * Define a task used by {BABYLON.AssetsManager} to load images
  86647. */
  86648. var ImageAssetTask = /** @class */ (function (_super) {
  86649. __extends(ImageAssetTask, _super);
  86650. /**
  86651. * Creates a new ImageAssetTask
  86652. * @param name defines the name of the task
  86653. * @param url defines the location of the image to load
  86654. */
  86655. function ImageAssetTask(
  86656. /**
  86657. * Defines the name of the task
  86658. */
  86659. name,
  86660. /**
  86661. * Defines the location of the image to load
  86662. */
  86663. url) {
  86664. var _this = _super.call(this, name) || this;
  86665. _this.name = name;
  86666. _this.url = url;
  86667. return _this;
  86668. }
  86669. /**
  86670. * Execute the current task
  86671. * @param scene defines the scene where you want your assets to be loaded
  86672. * @param onSuccess is a callback called when the task is successfully executed
  86673. * @param onError is a callback called if an error occurs
  86674. */
  86675. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86676. var _this = this;
  86677. var img = new Image();
  86678. BABYLON.Tools.SetCorsBehavior(this.url, img);
  86679. img.onload = function () {
  86680. _this.image = img;
  86681. onSuccess();
  86682. };
  86683. img.onerror = function (err) {
  86684. onError("Error loading image", err);
  86685. };
  86686. img.src = this.url;
  86687. };
  86688. return ImageAssetTask;
  86689. }(AbstractAssetTask));
  86690. BABYLON.ImageAssetTask = ImageAssetTask;
  86691. /**
  86692. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  86693. */
  86694. var TextureAssetTask = /** @class */ (function (_super) {
  86695. __extends(TextureAssetTask, _super);
  86696. /**
  86697. * Creates a new TextureAssetTask object
  86698. * @param name defines the name of the task
  86699. * @param url defines the location of the file to load
  86700. * @param noMipmap defines if mipmap should not be generated (default is false)
  86701. * @param invertY defines if texture must be inverted on Y axis (default is false)
  86702. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86703. */
  86704. function TextureAssetTask(
  86705. /**
  86706. * Defines the name of the task
  86707. */
  86708. name,
  86709. /**
  86710. * Defines the location of the file to load
  86711. */
  86712. url,
  86713. /**
  86714. * Defines if mipmap should not be generated (default is false)
  86715. */
  86716. noMipmap,
  86717. /**
  86718. * Defines if texture must be inverted on Y axis (default is false)
  86719. */
  86720. invertY,
  86721. /**
  86722. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86723. */
  86724. samplingMode) {
  86725. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86726. var _this = _super.call(this, name) || this;
  86727. _this.name = name;
  86728. _this.url = url;
  86729. _this.noMipmap = noMipmap;
  86730. _this.invertY = invertY;
  86731. _this.samplingMode = samplingMode;
  86732. return _this;
  86733. }
  86734. /**
  86735. * Execute the current task
  86736. * @param scene defines the scene where you want your assets to be loaded
  86737. * @param onSuccess is a callback called when the task is successfully executed
  86738. * @param onError is a callback called if an error occurs
  86739. */
  86740. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86741. var onload = function () {
  86742. onSuccess();
  86743. };
  86744. var onerror = function (message, exception) {
  86745. onError(message, exception);
  86746. };
  86747. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  86748. };
  86749. return TextureAssetTask;
  86750. }(AbstractAssetTask));
  86751. BABYLON.TextureAssetTask = TextureAssetTask;
  86752. /**
  86753. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  86754. */
  86755. var CubeTextureAssetTask = /** @class */ (function (_super) {
  86756. __extends(CubeTextureAssetTask, _super);
  86757. /**
  86758. * Creates a new CubeTextureAssetTask
  86759. * @param name defines the name of the task
  86760. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86761. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86762. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86763. * @param files defines the explicit list of files (undefined by default)
  86764. */
  86765. function CubeTextureAssetTask(
  86766. /**
  86767. * Defines the name of the task
  86768. */
  86769. name,
  86770. /**
  86771. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86772. */
  86773. url,
  86774. /**
  86775. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86776. */
  86777. extensions,
  86778. /**
  86779. * Defines if mipmaps should not be generated (default is false)
  86780. */
  86781. noMipmap,
  86782. /**
  86783. * Defines the explicit list of files (undefined by default)
  86784. */
  86785. files) {
  86786. var _this = _super.call(this, name) || this;
  86787. _this.name = name;
  86788. _this.url = url;
  86789. _this.extensions = extensions;
  86790. _this.noMipmap = noMipmap;
  86791. _this.files = files;
  86792. return _this;
  86793. }
  86794. /**
  86795. * Execute the current task
  86796. * @param scene defines the scene where you want your assets to be loaded
  86797. * @param onSuccess is a callback called when the task is successfully executed
  86798. * @param onError is a callback called if an error occurs
  86799. */
  86800. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86801. var onload = function () {
  86802. onSuccess();
  86803. };
  86804. var onerror = function (message, exception) {
  86805. onError(message, exception);
  86806. };
  86807. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  86808. };
  86809. return CubeTextureAssetTask;
  86810. }(AbstractAssetTask));
  86811. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  86812. /**
  86813. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  86814. */
  86815. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  86816. __extends(HDRCubeTextureAssetTask, _super);
  86817. /**
  86818. * Creates a new HDRCubeTextureAssetTask object
  86819. * @param name defines the name of the task
  86820. * @param url defines the location of the file to load
  86821. * @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.
  86822. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86823. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86824. * @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)
  86825. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86826. */
  86827. function HDRCubeTextureAssetTask(
  86828. /**
  86829. * Defines the name of the task
  86830. */
  86831. name,
  86832. /**
  86833. * Defines the location of the file to load
  86834. */
  86835. url,
  86836. /**
  86837. * 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.
  86838. */
  86839. size,
  86840. /**
  86841. * Defines if mipmaps should not be generated (default is false)
  86842. */
  86843. noMipmap,
  86844. /**
  86845. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86846. */
  86847. generateHarmonics,
  86848. /**
  86849. * 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)
  86850. */
  86851. useInGammaSpace,
  86852. /**
  86853. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86854. */
  86855. usePMREMGenerator) {
  86856. if (noMipmap === void 0) { noMipmap = false; }
  86857. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86858. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86859. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86860. var _this = _super.call(this, name) || this;
  86861. _this.name = name;
  86862. _this.url = url;
  86863. _this.size = size;
  86864. _this.noMipmap = noMipmap;
  86865. _this.generateHarmonics = generateHarmonics;
  86866. _this.useInGammaSpace = useInGammaSpace;
  86867. _this.usePMREMGenerator = usePMREMGenerator;
  86868. return _this;
  86869. }
  86870. /**
  86871. * Execute the current task
  86872. * @param scene defines the scene where you want your assets to be loaded
  86873. * @param onSuccess is a callback called when the task is successfully executed
  86874. * @param onError is a callback called if an error occurs
  86875. */
  86876. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86877. var onload = function () {
  86878. onSuccess();
  86879. };
  86880. var onerror = function (message, exception) {
  86881. onError(message, exception);
  86882. };
  86883. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  86884. };
  86885. return HDRCubeTextureAssetTask;
  86886. }(AbstractAssetTask));
  86887. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  86888. /**
  86889. * This class can be used to easily import assets into a scene
  86890. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  86891. */
  86892. var AssetsManager = /** @class */ (function () {
  86893. /**
  86894. * Creates a new AssetsManager
  86895. * @param scene defines the scene to work on
  86896. */
  86897. function AssetsManager(scene) {
  86898. this._isLoading = false;
  86899. this._tasks = new Array();
  86900. this._waitingTasksCount = 0;
  86901. this._totalTasksCount = 0;
  86902. /**
  86903. * Observable called when all tasks are processed
  86904. */
  86905. this.onTaskSuccessObservable = new BABYLON.Observable();
  86906. /**
  86907. * Observable called when a task had an error
  86908. */
  86909. this.onTaskErrorObservable = new BABYLON.Observable();
  86910. /**
  86911. * Observable called when a task is successful
  86912. */
  86913. this.onTasksDoneObservable = new BABYLON.Observable();
  86914. /**
  86915. * Observable called when a task is done (whatever the result is)
  86916. */
  86917. this.onProgressObservable = new BABYLON.Observable();
  86918. /**
  86919. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  86920. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  86921. */
  86922. this.useDefaultLoadingScreen = true;
  86923. this._scene = scene;
  86924. }
  86925. /**
  86926. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  86927. * @param taskName defines the name of the new task
  86928. * @param meshesNames defines the name of meshes to load
  86929. * @param rootUrl defines the root url to use to locate files
  86930. * @param sceneFilename defines the filename of the scene file
  86931. * @returns a new {BABYLON.MeshAssetTask} object
  86932. */
  86933. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  86934. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  86935. this._tasks.push(task);
  86936. return task;
  86937. };
  86938. /**
  86939. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  86940. * @param taskName defines the name of the new task
  86941. * @param url defines the url of the file to load
  86942. * @returns a new {BABYLON.TextFileAssetTask} object
  86943. */
  86944. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  86945. var task = new TextFileAssetTask(taskName, url);
  86946. this._tasks.push(task);
  86947. return task;
  86948. };
  86949. /**
  86950. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  86951. * @param taskName defines the name of the new task
  86952. * @param url defines the url of the file to load
  86953. * @returns a new {BABYLON.BinaryFileAssetTask} object
  86954. */
  86955. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  86956. var task = new BinaryFileAssetTask(taskName, url);
  86957. this._tasks.push(task);
  86958. return task;
  86959. };
  86960. /**
  86961. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  86962. * @param taskName defines the name of the new task
  86963. * @param url defines the url of the file to load
  86964. * @returns a new {BABYLON.ImageAssetTask} object
  86965. */
  86966. AssetsManager.prototype.addImageTask = function (taskName, url) {
  86967. var task = new ImageAssetTask(taskName, url);
  86968. this._tasks.push(task);
  86969. return task;
  86970. };
  86971. /**
  86972. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  86973. * @param taskName defines the name of the new task
  86974. * @param url defines the url of the file to load
  86975. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86976. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  86977. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  86978. * @returns a new {BABYLON.TextureAssetTask} object
  86979. */
  86980. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  86981. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86982. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  86983. this._tasks.push(task);
  86984. return task;
  86985. };
  86986. /**
  86987. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  86988. * @param taskName defines the name of the new task
  86989. * @param url defines the url of the file to load
  86990. * @param extensions defines the extension to use to load the cube map (can be null)
  86991. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86992. * @param files defines the list of files to load (can be null)
  86993. * @returns a new {BABYLON.CubeTextureAssetTask} object
  86994. */
  86995. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  86996. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  86997. this._tasks.push(task);
  86998. return task;
  86999. };
  87000. /**
  87001. *
  87002. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  87003. * @param taskName defines the name of the new task
  87004. * @param url defines the url of the file to load
  87005. * @param size defines the size you want for the cubemap (can be null)
  87006. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87007. * @param generateHarmonics defines if you want to automatically generate (true by default)
  87008. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  87009. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  87010. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  87011. */
  87012. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  87013. if (noMipmap === void 0) { noMipmap = false; }
  87014. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87015. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87016. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87017. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  87018. this._tasks.push(task);
  87019. return task;
  87020. };
  87021. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  87022. var _this = this;
  87023. this._waitingTasksCount--;
  87024. try {
  87025. if (task.taskState === AssetTaskState.DONE) {
  87026. // Let's remove successfull tasks
  87027. BABYLON.Tools.SetImmediate(function () {
  87028. var index = _this._tasks.indexOf(task);
  87029. if (index > -1) {
  87030. _this._tasks.splice(index, 1);
  87031. }
  87032. });
  87033. }
  87034. if (this.onProgress) {
  87035. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  87036. }
  87037. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  87038. }
  87039. catch (e) {
  87040. BABYLON.Tools.Error("Error running progress callbacks.");
  87041. console.log(e);
  87042. }
  87043. if (this._waitingTasksCount === 0) {
  87044. try {
  87045. if (this.onFinish) {
  87046. this.onFinish(this._tasks);
  87047. }
  87048. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87049. }
  87050. catch (e) {
  87051. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  87052. console.log(e);
  87053. }
  87054. this._isLoading = false;
  87055. this._scene.getEngine().hideLoadingUI();
  87056. }
  87057. };
  87058. AssetsManager.prototype._runTask = function (task) {
  87059. var _this = this;
  87060. var done = function () {
  87061. try {
  87062. if (_this.onTaskSuccess) {
  87063. _this.onTaskSuccess(task);
  87064. }
  87065. _this.onTaskSuccessObservable.notifyObservers(task);
  87066. _this._decreaseWaitingTasksCount(task);
  87067. }
  87068. catch (e) {
  87069. error("Error executing task success callbacks", e);
  87070. }
  87071. };
  87072. var error = function (message, exception) {
  87073. task._setErrorObject(message, exception);
  87074. if (_this.onTaskError) {
  87075. _this.onTaskError(task);
  87076. }
  87077. _this.onTaskErrorObservable.notifyObservers(task);
  87078. _this._decreaseWaitingTasksCount(task);
  87079. };
  87080. task.run(this._scene, done, error);
  87081. };
  87082. /**
  87083. * Reset the {BABYLON.AssetsManager} and remove all tasks
  87084. * @return the current instance of the {BABYLON.AssetsManager}
  87085. */
  87086. AssetsManager.prototype.reset = function () {
  87087. this._isLoading = false;
  87088. this._tasks = new Array();
  87089. return this;
  87090. };
  87091. /**
  87092. * Start the loading process
  87093. * @return the current instance of the {BABYLON.AssetsManager}
  87094. */
  87095. AssetsManager.prototype.load = function () {
  87096. if (this._isLoading) {
  87097. return this;
  87098. }
  87099. this._isLoading = true;
  87100. this._waitingTasksCount = this._tasks.length;
  87101. this._totalTasksCount = this._tasks.length;
  87102. if (this._waitingTasksCount === 0) {
  87103. this._isLoading = false;
  87104. if (this.onFinish) {
  87105. this.onFinish(this._tasks);
  87106. }
  87107. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87108. return this;
  87109. }
  87110. if (this.useDefaultLoadingScreen) {
  87111. this._scene.getEngine().displayLoadingUI();
  87112. }
  87113. for (var index = 0; index < this._tasks.length; index++) {
  87114. var task = this._tasks[index];
  87115. this._runTask(task);
  87116. }
  87117. return this;
  87118. };
  87119. return AssetsManager;
  87120. }());
  87121. BABYLON.AssetsManager = AssetsManager;
  87122. })(BABYLON || (BABYLON = {}));
  87123. //# sourceMappingURL=babylon.assetsManager.js.map
  87124. var BABYLON;
  87125. (function (BABYLON) {
  87126. var serializedGeometries = [];
  87127. var serializeGeometry = function (geometry, serializationGeometries) {
  87128. if (serializedGeometries[geometry.id]) {
  87129. return;
  87130. }
  87131. if (geometry.doNotSerialize) {
  87132. return;
  87133. }
  87134. if (geometry instanceof BABYLON.BoxGeometry) {
  87135. serializationGeometries.boxes.push(geometry.serialize());
  87136. }
  87137. else if (geometry instanceof BABYLON.SphereGeometry) {
  87138. serializationGeometries.spheres.push(geometry.serialize());
  87139. }
  87140. else if (geometry instanceof BABYLON.CylinderGeometry) {
  87141. serializationGeometries.cylinders.push(geometry.serialize());
  87142. }
  87143. else if (geometry instanceof BABYLON.TorusGeometry) {
  87144. serializationGeometries.toruses.push(geometry.serialize());
  87145. }
  87146. else if (geometry instanceof BABYLON.GroundGeometry) {
  87147. serializationGeometries.grounds.push(geometry.serialize());
  87148. }
  87149. else if (geometry instanceof BABYLON.Plane) {
  87150. serializationGeometries.planes.push(geometry.serialize());
  87151. }
  87152. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  87153. serializationGeometries.torusKnots.push(geometry.serialize());
  87154. }
  87155. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  87156. throw new Error("Unknown primitive type");
  87157. }
  87158. else {
  87159. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  87160. }
  87161. serializedGeometries[geometry.id] = true;
  87162. };
  87163. var serializeMesh = function (mesh, serializationScene) {
  87164. var serializationObject = {};
  87165. // Geometry
  87166. var geometry = mesh._geometry;
  87167. if (geometry) {
  87168. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  87169. // 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
  87170. serializeGeometry(geometry, serializationScene.geometries);
  87171. }
  87172. }
  87173. // Custom
  87174. if (mesh.serialize) {
  87175. mesh.serialize(serializationObject);
  87176. }
  87177. return serializationObject;
  87178. };
  87179. var finalizeSingleMesh = function (mesh, serializationObject) {
  87180. //only works if the mesh is already loaded
  87181. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87182. //serialize material
  87183. if (mesh.material) {
  87184. if (mesh.material instanceof BABYLON.StandardMaterial) {
  87185. serializationObject.materials = serializationObject.materials || [];
  87186. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87187. serializationObject.materials.push(mesh.material.serialize());
  87188. }
  87189. }
  87190. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  87191. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  87192. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87193. serializationObject.multiMaterials.push(mesh.material.serialize());
  87194. }
  87195. }
  87196. }
  87197. //serialize geometry
  87198. var geometry = mesh._geometry;
  87199. if (geometry) {
  87200. if (!serializationObject.geometries) {
  87201. serializationObject.geometries = {};
  87202. serializationObject.geometries.boxes = [];
  87203. serializationObject.geometries.spheres = [];
  87204. serializationObject.geometries.cylinders = [];
  87205. serializationObject.geometries.toruses = [];
  87206. serializationObject.geometries.grounds = [];
  87207. serializationObject.geometries.planes = [];
  87208. serializationObject.geometries.torusKnots = [];
  87209. serializationObject.geometries.vertexData = [];
  87210. }
  87211. serializeGeometry(geometry, serializationObject.geometries);
  87212. }
  87213. // Skeletons
  87214. if (mesh.skeleton) {
  87215. serializationObject.skeletons = serializationObject.skeletons || [];
  87216. serializationObject.skeletons.push(mesh.skeleton.serialize());
  87217. }
  87218. //serialize the actual mesh
  87219. serializationObject.meshes = serializationObject.meshes || [];
  87220. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87221. }
  87222. };
  87223. var SceneSerializer = /** @class */ (function () {
  87224. function SceneSerializer() {
  87225. }
  87226. SceneSerializer.ClearCache = function () {
  87227. serializedGeometries = [];
  87228. };
  87229. SceneSerializer.Serialize = function (scene) {
  87230. var serializationObject = {};
  87231. SceneSerializer.ClearCache();
  87232. // Scene
  87233. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  87234. serializationObject.autoClear = scene.autoClear;
  87235. serializationObject.clearColor = scene.clearColor.asArray();
  87236. serializationObject.ambientColor = scene.ambientColor.asArray();
  87237. serializationObject.gravity = scene.gravity.asArray();
  87238. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  87239. serializationObject.workerCollisions = scene.workerCollisions;
  87240. // Fog
  87241. if (scene.fogMode && scene.fogMode !== 0) {
  87242. serializationObject.fogMode = scene.fogMode;
  87243. serializationObject.fogColor = scene.fogColor.asArray();
  87244. serializationObject.fogStart = scene.fogStart;
  87245. serializationObject.fogEnd = scene.fogEnd;
  87246. serializationObject.fogDensity = scene.fogDensity;
  87247. }
  87248. //Physics
  87249. if (scene.isPhysicsEnabled()) {
  87250. var physicEngine = scene.getPhysicsEngine();
  87251. if (physicEngine) {
  87252. serializationObject.physicsEnabled = true;
  87253. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  87254. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  87255. }
  87256. }
  87257. // Metadata
  87258. if (scene.metadata) {
  87259. serializationObject.metadata = scene.metadata;
  87260. }
  87261. // Morph targets
  87262. serializationObject.morphTargetManagers = [];
  87263. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  87264. var abstractMesh = _a[_i];
  87265. var manager = abstractMesh.morphTargetManager;
  87266. if (manager) {
  87267. serializationObject.morphTargetManagers.push(manager.serialize());
  87268. }
  87269. }
  87270. // Lights
  87271. serializationObject.lights = [];
  87272. var index;
  87273. var light;
  87274. for (index = 0; index < scene.lights.length; index++) {
  87275. light = scene.lights[index];
  87276. if (!light.doNotSerialize) {
  87277. serializationObject.lights.push(light.serialize());
  87278. }
  87279. }
  87280. // Cameras
  87281. serializationObject.cameras = [];
  87282. for (index = 0; index < scene.cameras.length; index++) {
  87283. var camera = scene.cameras[index];
  87284. if (!camera.doNotSerialize) {
  87285. serializationObject.cameras.push(camera.serialize());
  87286. }
  87287. }
  87288. if (scene.activeCamera) {
  87289. serializationObject.activeCameraID = scene.activeCamera.id;
  87290. }
  87291. // Animations
  87292. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  87293. // Materials
  87294. serializationObject.materials = [];
  87295. serializationObject.multiMaterials = [];
  87296. var material;
  87297. for (index = 0; index < scene.materials.length; index++) {
  87298. material = scene.materials[index];
  87299. if (!material.doNotSerialize) {
  87300. serializationObject.materials.push(material.serialize());
  87301. }
  87302. }
  87303. // MultiMaterials
  87304. serializationObject.multiMaterials = [];
  87305. for (index = 0; index < scene.multiMaterials.length; index++) {
  87306. var multiMaterial = scene.multiMaterials[index];
  87307. serializationObject.multiMaterials.push(multiMaterial.serialize());
  87308. }
  87309. // Environment texture
  87310. if (scene.environmentTexture) {
  87311. serializationObject.environmentTexture = scene.environmentTexture.name;
  87312. }
  87313. // Skeletons
  87314. serializationObject.skeletons = [];
  87315. for (index = 0; index < scene.skeletons.length; index++) {
  87316. var skeleton = scene.skeletons[index];
  87317. if (!skeleton.doNotSerialize) {
  87318. serializationObject.skeletons.push(skeleton.serialize());
  87319. }
  87320. }
  87321. // Transform nodes
  87322. serializationObject.transformNodes = [];
  87323. for (index = 0; index < scene.transformNodes.length; index++) {
  87324. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  87325. }
  87326. // Geometries
  87327. serializationObject.geometries = {};
  87328. serializationObject.geometries.boxes = [];
  87329. serializationObject.geometries.spheres = [];
  87330. serializationObject.geometries.cylinders = [];
  87331. serializationObject.geometries.toruses = [];
  87332. serializationObject.geometries.grounds = [];
  87333. serializationObject.geometries.planes = [];
  87334. serializationObject.geometries.torusKnots = [];
  87335. serializationObject.geometries.vertexData = [];
  87336. serializedGeometries = [];
  87337. var geometries = scene.getGeometries();
  87338. for (index = 0; index < geometries.length; index++) {
  87339. var geometry = geometries[index];
  87340. if (geometry.isReady()) {
  87341. serializeGeometry(geometry, serializationObject.geometries);
  87342. }
  87343. }
  87344. // Meshes
  87345. serializationObject.meshes = [];
  87346. for (index = 0; index < scene.meshes.length; index++) {
  87347. var abstractMesh = scene.meshes[index];
  87348. if (abstractMesh instanceof BABYLON.Mesh) {
  87349. var mesh = abstractMesh;
  87350. if (!mesh.doNotSerialize) {
  87351. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87352. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87353. }
  87354. }
  87355. }
  87356. }
  87357. // Particles Systems
  87358. serializationObject.particleSystems = [];
  87359. for (index = 0; index < scene.particleSystems.length; index++) {
  87360. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  87361. }
  87362. // Lens flares
  87363. serializationObject.lensFlareSystems = [];
  87364. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  87365. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  87366. }
  87367. // Shadows
  87368. serializationObject.shadowGenerators = [];
  87369. for (index = 0; index < scene.lights.length; index++) {
  87370. light = scene.lights[index];
  87371. var shadowGenerator = light.getShadowGenerator();
  87372. if (shadowGenerator) {
  87373. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  87374. }
  87375. }
  87376. // Action Manager
  87377. if (scene.actionManager) {
  87378. serializationObject.actions = scene.actionManager.serialize("scene");
  87379. }
  87380. // Audio
  87381. serializationObject.sounds = [];
  87382. for (index = 0; index < scene.soundTracks.length; index++) {
  87383. var soundtrack = scene.soundTracks[index];
  87384. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  87385. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  87386. }
  87387. }
  87388. return serializationObject;
  87389. };
  87390. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  87391. if (withParents === void 0) { withParents = false; }
  87392. if (withChildren === void 0) { withChildren = false; }
  87393. var serializationObject = {};
  87394. SceneSerializer.ClearCache();
  87395. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  87396. if (withParents || withChildren) {
  87397. //deliberate for loop! not for each, appended should be processed as well.
  87398. for (var i = 0; i < toSerialize.length; ++i) {
  87399. if (withChildren) {
  87400. toSerialize[i].getDescendants().forEach(function (node) {
  87401. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  87402. toSerialize.push(node);
  87403. }
  87404. });
  87405. }
  87406. //make sure the array doesn't contain the object already
  87407. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  87408. toSerialize.push(toSerialize[i].parent);
  87409. }
  87410. }
  87411. }
  87412. toSerialize.forEach(function (mesh) {
  87413. finalizeSingleMesh(mesh, serializationObject);
  87414. });
  87415. return serializationObject;
  87416. };
  87417. return SceneSerializer;
  87418. }());
  87419. BABYLON.SceneSerializer = SceneSerializer;
  87420. })(BABYLON || (BABYLON = {}));
  87421. //# sourceMappingURL=babylon.sceneSerializer.js.map
  87422. var BABYLON;
  87423. (function (BABYLON) {
  87424. var ReflectionProbe = /** @class */ (function () {
  87425. function ReflectionProbe(name, size, scene, generateMipMaps) {
  87426. if (generateMipMaps === void 0) { generateMipMaps = true; }
  87427. var _this = this;
  87428. this.name = name;
  87429. this._viewMatrix = BABYLON.Matrix.Identity();
  87430. this._target = BABYLON.Vector3.Zero();
  87431. this._add = BABYLON.Vector3.Zero();
  87432. this._invertYAxis = false;
  87433. this.position = BABYLON.Vector3.Zero();
  87434. this._scene = scene;
  87435. this._scene.reflectionProbes.push(this);
  87436. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  87437. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  87438. switch (faceIndex) {
  87439. case 0:
  87440. _this._add.copyFromFloats(1, 0, 0);
  87441. break;
  87442. case 1:
  87443. _this._add.copyFromFloats(-1, 0, 0);
  87444. break;
  87445. case 2:
  87446. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  87447. break;
  87448. case 3:
  87449. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  87450. break;
  87451. case 4:
  87452. _this._add.copyFromFloats(0, 0, 1);
  87453. break;
  87454. case 5:
  87455. _this._add.copyFromFloats(0, 0, -1);
  87456. break;
  87457. }
  87458. if (_this._attachedMesh) {
  87459. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  87460. }
  87461. _this.position.addToRef(_this._add, _this._target);
  87462. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  87463. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  87464. scene._forcedViewPosition = _this.position;
  87465. });
  87466. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  87467. scene._forcedViewPosition = null;
  87468. scene.updateTransformMatrix(true);
  87469. });
  87470. if (scene.activeCamera) {
  87471. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87472. }
  87473. }
  87474. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  87475. get: function () {
  87476. return this._renderTargetTexture.samples;
  87477. },
  87478. set: function (value) {
  87479. this._renderTargetTexture.samples = value;
  87480. },
  87481. enumerable: true,
  87482. configurable: true
  87483. });
  87484. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  87485. get: function () {
  87486. return this._renderTargetTexture.refreshRate;
  87487. },
  87488. set: function (value) {
  87489. this._renderTargetTexture.refreshRate = value;
  87490. },
  87491. enumerable: true,
  87492. configurable: true
  87493. });
  87494. ReflectionProbe.prototype.getScene = function () {
  87495. return this._scene;
  87496. };
  87497. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  87498. get: function () {
  87499. return this._renderTargetTexture;
  87500. },
  87501. enumerable: true,
  87502. configurable: true
  87503. });
  87504. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  87505. get: function () {
  87506. return this._renderTargetTexture.renderList;
  87507. },
  87508. enumerable: true,
  87509. configurable: true
  87510. });
  87511. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  87512. this._attachedMesh = mesh;
  87513. };
  87514. /**
  87515. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  87516. *
  87517. * @param renderingGroupId The rendering group id corresponding to its index
  87518. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  87519. */
  87520. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  87521. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  87522. };
  87523. ReflectionProbe.prototype.dispose = function () {
  87524. var index = this._scene.reflectionProbes.indexOf(this);
  87525. if (index !== -1) {
  87526. // Remove from the scene if found
  87527. this._scene.reflectionProbes.splice(index, 1);
  87528. }
  87529. if (this._renderTargetTexture) {
  87530. this._renderTargetTexture.dispose();
  87531. this._renderTargetTexture = null;
  87532. }
  87533. };
  87534. return ReflectionProbe;
  87535. }());
  87536. BABYLON.ReflectionProbe = ReflectionProbe;
  87537. })(BABYLON || (BABYLON = {}));
  87538. //# sourceMappingURL=babylon.reflectionProbe.js.map
  87539. var BABYLON;
  87540. (function (BABYLON) {
  87541. var Layer = /** @class */ (function () {
  87542. function Layer(name, imgUrl, scene, isBackground, color) {
  87543. this.name = name;
  87544. this.scale = new BABYLON.Vector2(1, 1);
  87545. this.offset = new BABYLON.Vector2(0, 0);
  87546. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  87547. this.layerMask = 0x0FFFFFFF;
  87548. this._vertexBuffers = {};
  87549. // Events
  87550. /**
  87551. * An event triggered when the layer is disposed.
  87552. * @type {BABYLON.Observable}
  87553. */
  87554. this.onDisposeObservable = new BABYLON.Observable();
  87555. /**
  87556. * An event triggered before rendering the scene
  87557. * @type {BABYLON.Observable}
  87558. */
  87559. this.onBeforeRenderObservable = new BABYLON.Observable();
  87560. /**
  87561. * An event triggered after rendering the scene
  87562. * @type {BABYLON.Observable}
  87563. */
  87564. this.onAfterRenderObservable = new BABYLON.Observable();
  87565. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  87566. this.isBackground = isBackground === undefined ? true : isBackground;
  87567. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  87568. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  87569. this._scene.layers.push(this);
  87570. var engine = this._scene.getEngine();
  87571. // VBO
  87572. var vertices = [];
  87573. vertices.push(1, 1);
  87574. vertices.push(-1, 1);
  87575. vertices.push(-1, -1);
  87576. vertices.push(1, -1);
  87577. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87578. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  87579. this._createIndexBuffer();
  87580. // Effects
  87581. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  87582. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  87583. }
  87584. Object.defineProperty(Layer.prototype, "onDispose", {
  87585. set: function (callback) {
  87586. if (this._onDisposeObserver) {
  87587. this.onDisposeObservable.remove(this._onDisposeObserver);
  87588. }
  87589. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  87590. },
  87591. enumerable: true,
  87592. configurable: true
  87593. });
  87594. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  87595. set: function (callback) {
  87596. if (this._onBeforeRenderObserver) {
  87597. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  87598. }
  87599. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  87600. },
  87601. enumerable: true,
  87602. configurable: true
  87603. });
  87604. Object.defineProperty(Layer.prototype, "onAfterRender", {
  87605. set: function (callback) {
  87606. if (this._onAfterRenderObserver) {
  87607. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87608. }
  87609. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  87610. },
  87611. enumerable: true,
  87612. configurable: true
  87613. });
  87614. Layer.prototype._createIndexBuffer = function () {
  87615. var engine = this._scene.getEngine();
  87616. // Indices
  87617. var indices = [];
  87618. indices.push(0);
  87619. indices.push(1);
  87620. indices.push(2);
  87621. indices.push(0);
  87622. indices.push(2);
  87623. indices.push(3);
  87624. this._indexBuffer = engine.createIndexBuffer(indices);
  87625. };
  87626. Layer.prototype._rebuild = function () {
  87627. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87628. if (vb) {
  87629. vb._rebuild();
  87630. }
  87631. this._createIndexBuffer();
  87632. };
  87633. Layer.prototype.render = function () {
  87634. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  87635. // Check
  87636. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  87637. return;
  87638. var engine = this._scene.getEngine();
  87639. this.onBeforeRenderObservable.notifyObservers(this);
  87640. // Render
  87641. engine.enableEffect(currentEffect);
  87642. engine.setState(false);
  87643. // Texture
  87644. currentEffect.setTexture("textureSampler", this.texture);
  87645. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  87646. // Color
  87647. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  87648. // Scale / offset
  87649. currentEffect.setVector2("offset", this.offset);
  87650. currentEffect.setVector2("scale", this.scale);
  87651. // VBOs
  87652. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  87653. // Draw order
  87654. if (!this.alphaTest) {
  87655. engine.setAlphaMode(this.alphaBlendingMode);
  87656. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87657. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87658. }
  87659. else {
  87660. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87661. }
  87662. this.onAfterRenderObservable.notifyObservers(this);
  87663. };
  87664. Layer.prototype.dispose = function () {
  87665. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87666. if (vertexBuffer) {
  87667. vertexBuffer.dispose();
  87668. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87669. }
  87670. if (this._indexBuffer) {
  87671. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87672. this._indexBuffer = null;
  87673. }
  87674. if (this.texture) {
  87675. this.texture.dispose();
  87676. this.texture = null;
  87677. }
  87678. // Remove from scene
  87679. var index = this._scene.layers.indexOf(this);
  87680. this._scene.layers.splice(index, 1);
  87681. // Callback
  87682. this.onDisposeObservable.notifyObservers(this);
  87683. this.onDisposeObservable.clear();
  87684. this.onAfterRenderObservable.clear();
  87685. this.onBeforeRenderObservable.clear();
  87686. };
  87687. return Layer;
  87688. }());
  87689. BABYLON.Layer = Layer;
  87690. })(BABYLON || (BABYLON = {}));
  87691. //# sourceMappingURL=babylon.layer.js.map
  87692. var BABYLON;
  87693. (function (BABYLON) {
  87694. var TextureTools = /** @class */ (function () {
  87695. function TextureTools() {
  87696. }
  87697. /**
  87698. * Uses the GPU to create a copy texture rescaled at a given size
  87699. * @param texture Texture to copy from
  87700. * @param width Desired width
  87701. * @param height Desired height
  87702. * @return Generated texture
  87703. */
  87704. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  87705. if (useBilinearMode === void 0) { useBilinearMode = true; }
  87706. var scene = texture.getScene();
  87707. var engine = scene.getEngine();
  87708. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  87709. rtt.wrapU = texture.wrapU;
  87710. rtt.wrapV = texture.wrapV;
  87711. rtt.uOffset = texture.uOffset;
  87712. rtt.vOffset = texture.vOffset;
  87713. rtt.uScale = texture.uScale;
  87714. rtt.vScale = texture.vScale;
  87715. rtt.uAng = texture.uAng;
  87716. rtt.vAng = texture.vAng;
  87717. rtt.wAng = texture.wAng;
  87718. rtt.coordinatesIndex = texture.coordinatesIndex;
  87719. rtt.level = texture.level;
  87720. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  87721. rtt._texture.isReady = false;
  87722. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87723. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87724. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87725. passPostProcess.getEffect().executeWhenCompiled(function () {
  87726. passPostProcess.onApply = function (effect) {
  87727. effect.setTexture("textureSampler", texture);
  87728. };
  87729. var internalTexture = rtt.getInternalTexture();
  87730. if (internalTexture) {
  87731. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  87732. engine.unBindFramebuffer(internalTexture);
  87733. rtt.disposeFramebufferObjects();
  87734. passPostProcess.dispose();
  87735. internalTexture.isReady = true;
  87736. }
  87737. });
  87738. return rtt;
  87739. };
  87740. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  87741. if (!scene._environmentBRDFTexture) {
  87742. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87743. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87744. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87745. scene._environmentBRDFTexture = texture;
  87746. }
  87747. return scene._environmentBRDFTexture;
  87748. };
  87749. 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=";
  87750. return TextureTools;
  87751. }());
  87752. BABYLON.TextureTools = TextureTools;
  87753. })(BABYLON || (BABYLON = {}));
  87754. //# sourceMappingURL=babylon.textureTools.js.map
  87755. var BABYLON;
  87756. (function (BABYLON) {
  87757. var FramingBehavior = /** @class */ (function () {
  87758. function FramingBehavior() {
  87759. this._mode = FramingBehavior.FitFrustumSidesMode;
  87760. this._radiusScale = 1.0;
  87761. this._positionScale = 0.5;
  87762. this._defaultElevation = 0.3;
  87763. this._elevationReturnTime = 1500;
  87764. this._elevationReturnWaitTime = 1000;
  87765. this._zoomStopsAnimation = false;
  87766. this._framingTime = 1500;
  87767. this._isPointerDown = false;
  87768. this._lastInteractionTime = -Infinity;
  87769. // Framing control
  87770. this._animatables = new Array();
  87771. this._betaIsAnimating = false;
  87772. }
  87773. Object.defineProperty(FramingBehavior.prototype, "name", {
  87774. get: function () {
  87775. return "Framing";
  87776. },
  87777. enumerable: true,
  87778. configurable: true
  87779. });
  87780. Object.defineProperty(FramingBehavior.prototype, "mode", {
  87781. /**
  87782. * Gets current mode used by the behavior.
  87783. */
  87784. get: function () {
  87785. return this._mode;
  87786. },
  87787. /**
  87788. * Sets the current mode used by the behavior
  87789. */
  87790. set: function (mode) {
  87791. this._mode = mode;
  87792. },
  87793. enumerable: true,
  87794. configurable: true
  87795. });
  87796. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  87797. /**
  87798. * Gets the scale applied to the radius
  87799. */
  87800. get: function () {
  87801. return this._radiusScale;
  87802. },
  87803. /**
  87804. * Sets the scale applied to the radius (1 by default)
  87805. */
  87806. set: function (radius) {
  87807. this._radiusScale = radius;
  87808. },
  87809. enumerable: true,
  87810. configurable: true
  87811. });
  87812. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  87813. /**
  87814. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87815. */
  87816. get: function () {
  87817. return this._positionScale;
  87818. },
  87819. /**
  87820. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87821. */
  87822. set: function (scale) {
  87823. this._positionScale = scale;
  87824. },
  87825. enumerable: true,
  87826. configurable: true
  87827. });
  87828. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  87829. /**
  87830. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87831. * behaviour is triggered, in radians.
  87832. */
  87833. get: function () {
  87834. return this._defaultElevation;
  87835. },
  87836. /**
  87837. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87838. * behaviour is triggered, in radians.
  87839. */
  87840. set: function (elevation) {
  87841. this._defaultElevation = elevation;
  87842. },
  87843. enumerable: true,
  87844. configurable: true
  87845. });
  87846. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  87847. /**
  87848. * Gets the time (in milliseconds) taken to return to the default beta position.
  87849. * Negative value indicates camera should not return to default.
  87850. */
  87851. get: function () {
  87852. return this._elevationReturnTime;
  87853. },
  87854. /**
  87855. * Sets the time (in milliseconds) taken to return to the default beta position.
  87856. * Negative value indicates camera should not return to default.
  87857. */
  87858. set: function (speed) {
  87859. this._elevationReturnTime = speed;
  87860. },
  87861. enumerable: true,
  87862. configurable: true
  87863. });
  87864. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  87865. /**
  87866. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87867. */
  87868. get: function () {
  87869. return this._elevationReturnWaitTime;
  87870. },
  87871. /**
  87872. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87873. */
  87874. set: function (time) {
  87875. this._elevationReturnWaitTime = time;
  87876. },
  87877. enumerable: true,
  87878. configurable: true
  87879. });
  87880. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  87881. /**
  87882. * Gets the flag that indicates if user zooming should stop animation.
  87883. */
  87884. get: function () {
  87885. return this._zoomStopsAnimation;
  87886. },
  87887. /**
  87888. * Sets the flag that indicates if user zooming should stop animation.
  87889. */
  87890. set: function (flag) {
  87891. this._zoomStopsAnimation = flag;
  87892. },
  87893. enumerable: true,
  87894. configurable: true
  87895. });
  87896. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  87897. /**
  87898. * Gets the transition time when framing the mesh, in milliseconds
  87899. */
  87900. get: function () {
  87901. return this._framingTime;
  87902. },
  87903. /**
  87904. * Sets the transition time when framing the mesh, in milliseconds
  87905. */
  87906. set: function (time) {
  87907. this._framingTime = time;
  87908. },
  87909. enumerable: true,
  87910. configurable: true
  87911. });
  87912. FramingBehavior.prototype.init = function () {
  87913. // Do notihng
  87914. };
  87915. FramingBehavior.prototype.attach = function (camera) {
  87916. var _this = this;
  87917. this._attachedCamera = camera;
  87918. var scene = this._attachedCamera.getScene();
  87919. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  87920. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87921. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87922. _this._isPointerDown = true;
  87923. return;
  87924. }
  87925. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87926. _this._isPointerDown = false;
  87927. }
  87928. });
  87929. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87930. if (mesh) {
  87931. _this.zoomOnMesh(mesh);
  87932. }
  87933. });
  87934. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87935. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87936. _this._applyUserInteraction();
  87937. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  87938. // back to the default position after a given timeout
  87939. _this._maintainCameraAboveGround();
  87940. });
  87941. };
  87942. FramingBehavior.prototype.detach = function () {
  87943. if (!this._attachedCamera) {
  87944. return;
  87945. }
  87946. var scene = this._attachedCamera.getScene();
  87947. if (this._onPrePointerObservableObserver) {
  87948. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87949. }
  87950. if (this._onAfterCheckInputsObserver) {
  87951. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87952. }
  87953. if (this._onMeshTargetChangedObserver) {
  87954. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87955. }
  87956. this._attachedCamera = null;
  87957. };
  87958. /**
  87959. * Targets the given mesh and updates zoom level accordingly.
  87960. * @param mesh The mesh to target.
  87961. * @param radius Optional. If a cached radius position already exists, overrides default.
  87962. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87963. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87964. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87965. */
  87966. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87967. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87968. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87969. mesh.computeWorldMatrix(true);
  87970. var boundingBox = mesh.getBoundingInfo().boundingBox;
  87971. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  87972. };
  87973. /**
  87974. * Targets the given mesh with its children and updates zoom level accordingly.
  87975. * @param mesh The mesh to target.
  87976. * @param radius Optional. If a cached radius position already exists, overrides default.
  87977. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87978. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87979. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87980. */
  87981. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87982. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87983. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87984. mesh.computeWorldMatrix(true);
  87985. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  87986. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  87987. };
  87988. /**
  87989. * Targets the given meshes with their children and updates zoom level accordingly.
  87990. * @param meshes The mesh to target.
  87991. * @param radius Optional. If a cached radius position already exists, overrides default.
  87992. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87993. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87994. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87995. */
  87996. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  87997. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87998. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87999. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  88000. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  88001. for (var i = 0; i < meshes.length; i++) {
  88002. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  88003. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  88004. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  88005. }
  88006. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  88007. };
  88008. /**
  88009. * Targets the given mesh and updates zoom level accordingly.
  88010. * @param mesh The mesh to target.
  88011. * @param radius Optional. If a cached radius position already exists, overrides default.
  88012. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88013. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88014. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88015. */
  88016. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  88017. var _this = this;
  88018. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88019. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88020. var zoomTarget;
  88021. if (!this._attachedCamera) {
  88022. return;
  88023. }
  88024. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  88025. var bottom = minimumWorld.y;
  88026. var top = maximumWorld.y;
  88027. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  88028. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  88029. if (focusOnOriginXZ) {
  88030. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  88031. }
  88032. else {
  88033. var centerWorld = minimumWorld.add(radiusWorld);
  88034. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  88035. }
  88036. if (!this._vectorTransition) {
  88037. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  88038. }
  88039. this._betaIsAnimating = true;
  88040. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  88041. if (animatable) {
  88042. this._animatables.push(animatable);
  88043. }
  88044. // sets the radius and lower radius bounds
  88045. // Small delta ensures camera is not always at lower zoom limit.
  88046. var radius = 0;
  88047. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  88048. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88049. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  88050. radius = position;
  88051. }
  88052. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88053. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88054. if (this._attachedCamera.lowerRadiusLimit === null) {
  88055. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  88056. }
  88057. }
  88058. // Set sensibilities
  88059. var extend = maximumWorld.subtract(minimumWorld).length();
  88060. this._attachedCamera.panningSensibility = 5000 / extend;
  88061. this._attachedCamera.wheelPrecision = 100 / radius;
  88062. // transition to new radius
  88063. if (!this._radiusTransition) {
  88064. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88065. }
  88066. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  88067. _this.stopAllAnimations();
  88068. if (onAnimationEnd) {
  88069. onAnimationEnd();
  88070. }
  88071. if (_this._attachedCamera) {
  88072. _this._attachedCamera.storeState();
  88073. }
  88074. });
  88075. if (animatable) {
  88076. this._animatables.push(animatable);
  88077. }
  88078. };
  88079. /**
  88080. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  88081. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  88082. * frustum width.
  88083. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  88084. * to fully enclose the mesh in the viewing frustum.
  88085. */
  88086. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  88087. var size = maximumWorld.subtract(minimumWorld);
  88088. var boxVectorGlobalDiagonal = size.length();
  88089. var frustumSlope = this._getFrustumSlope();
  88090. // Formula for setting distance
  88091. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  88092. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  88093. // Horizon distance
  88094. var radius = radiusWithoutFraming * this._radiusScale;
  88095. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  88096. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  88097. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  88098. var camera = this._attachedCamera;
  88099. if (!camera) {
  88100. return 0;
  88101. }
  88102. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88103. // Don't exceed the requested limit
  88104. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  88105. }
  88106. // Don't exceed the upper radius limit
  88107. if (camera.upperRadiusLimit) {
  88108. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  88109. }
  88110. return distance;
  88111. };
  88112. /**
  88113. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  88114. * is automatically returned to its default position (expected to be above ground plane).
  88115. */
  88116. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  88117. var _this = this;
  88118. if (this._elevationReturnTime < 0) {
  88119. return;
  88120. }
  88121. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  88122. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  88123. var limitBeta = Math.PI * 0.5;
  88124. // Bring the camera back up if below the ground plane
  88125. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  88126. this._betaIsAnimating = true;
  88127. //Transition to new position
  88128. this.stopAllAnimations();
  88129. if (!this._betaTransition) {
  88130. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88131. }
  88132. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  88133. _this._clearAnimationLocks();
  88134. _this.stopAllAnimations();
  88135. });
  88136. if (animatabe) {
  88137. this._animatables.push(animatabe);
  88138. }
  88139. }
  88140. };
  88141. /**
  88142. * Returns the frustum slope based on the canvas ratio and camera FOV
  88143. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  88144. */
  88145. FramingBehavior.prototype._getFrustumSlope = function () {
  88146. // Calculate the viewport ratio
  88147. // Aspect Ratio is Height/Width.
  88148. var camera = this._attachedCamera;
  88149. if (!camera) {
  88150. return BABYLON.Vector2.Zero();
  88151. }
  88152. var engine = camera.getScene().getEngine();
  88153. var aspectRatio = engine.getAspectRatio(camera);
  88154. // Camera FOV is the vertical field of view (top-bottom) in radians.
  88155. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  88156. var frustumSlopeY = Math.tan(camera.fov / 2);
  88157. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  88158. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  88159. // along the forward vector.
  88160. var frustumSlopeX = frustumSlopeY * aspectRatio;
  88161. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  88162. };
  88163. /**
  88164. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  88165. */
  88166. FramingBehavior.prototype._clearAnimationLocks = function () {
  88167. this._betaIsAnimating = false;
  88168. };
  88169. /**
  88170. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88171. */
  88172. FramingBehavior.prototype._applyUserInteraction = function () {
  88173. if (this.isUserIsMoving) {
  88174. this._lastInteractionTime = BABYLON.Tools.Now;
  88175. this.stopAllAnimations();
  88176. this._clearAnimationLocks();
  88177. }
  88178. };
  88179. /**
  88180. * Stops and removes all animations that have been applied to the camera
  88181. */
  88182. FramingBehavior.prototype.stopAllAnimations = function () {
  88183. if (this._attachedCamera) {
  88184. this._attachedCamera.animations = [];
  88185. }
  88186. while (this._animatables.length) {
  88187. if (this._animatables[0]) {
  88188. this._animatables[0].onAnimationEnd = null;
  88189. this._animatables[0].stop();
  88190. }
  88191. this._animatables.shift();
  88192. }
  88193. };
  88194. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  88195. /**
  88196. * Gets a value indicating if the user is moving the camera
  88197. */
  88198. get: function () {
  88199. if (!this._attachedCamera) {
  88200. return false;
  88201. }
  88202. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88203. this._attachedCamera.inertialBetaOffset !== 0 ||
  88204. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88205. this._attachedCamera.inertialPanningX !== 0 ||
  88206. this._attachedCamera.inertialPanningY !== 0 ||
  88207. this._isPointerDown;
  88208. },
  88209. enumerable: true,
  88210. configurable: true
  88211. });
  88212. /**
  88213. * The easing function used by animations
  88214. */
  88215. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  88216. /**
  88217. * The easing mode used by animations
  88218. */
  88219. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  88220. // Statics
  88221. /**
  88222. * The camera can move all the way towards the mesh.
  88223. */
  88224. FramingBehavior.IgnoreBoundsSizeMode = 0;
  88225. /**
  88226. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  88227. */
  88228. FramingBehavior.FitFrustumSidesMode = 1;
  88229. return FramingBehavior;
  88230. }());
  88231. BABYLON.FramingBehavior = FramingBehavior;
  88232. })(BABYLON || (BABYLON = {}));
  88233. //# sourceMappingURL=babylon.framingBehavior.js.map
  88234. var BABYLON;
  88235. (function (BABYLON) {
  88236. /**
  88237. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  88238. */
  88239. var BouncingBehavior = /** @class */ (function () {
  88240. function BouncingBehavior() {
  88241. /**
  88242. * The duration of the animation, in milliseconds
  88243. */
  88244. this.transitionDuration = 450;
  88245. /**
  88246. * Length of the distance animated by the transition when lower radius is reached
  88247. */
  88248. this.lowerRadiusTransitionRange = 2;
  88249. /**
  88250. * Length of the distance animated by the transition when upper radius is reached
  88251. */
  88252. this.upperRadiusTransitionRange = -2;
  88253. this._autoTransitionRange = false;
  88254. // Animations
  88255. this._radiusIsAnimating = false;
  88256. this._radiusBounceTransition = null;
  88257. this._animatables = new Array();
  88258. }
  88259. Object.defineProperty(BouncingBehavior.prototype, "name", {
  88260. get: function () {
  88261. return "Bouncing";
  88262. },
  88263. enumerable: true,
  88264. configurable: true
  88265. });
  88266. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  88267. /**
  88268. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88269. */
  88270. get: function () {
  88271. return this._autoTransitionRange;
  88272. },
  88273. /**
  88274. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88275. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  88276. */
  88277. set: function (value) {
  88278. var _this = this;
  88279. if (this._autoTransitionRange === value) {
  88280. return;
  88281. }
  88282. this._autoTransitionRange = value;
  88283. var camera = this._attachedCamera;
  88284. if (!camera) {
  88285. return;
  88286. }
  88287. if (value) {
  88288. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88289. if (!mesh) {
  88290. return;
  88291. }
  88292. mesh.computeWorldMatrix(true);
  88293. var diagonal = mesh.getBoundingInfo().diagonalLength;
  88294. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  88295. _this.upperRadiusTransitionRange = diagonal * 0.05;
  88296. });
  88297. }
  88298. else if (this._onMeshTargetChangedObserver) {
  88299. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88300. }
  88301. },
  88302. enumerable: true,
  88303. configurable: true
  88304. });
  88305. BouncingBehavior.prototype.init = function () {
  88306. // Do notihng
  88307. };
  88308. BouncingBehavior.prototype.attach = function (camera) {
  88309. var _this = this;
  88310. this._attachedCamera = camera;
  88311. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88312. if (!_this._attachedCamera) {
  88313. return;
  88314. }
  88315. // Add the bounce animation to the lower radius limit
  88316. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  88317. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  88318. }
  88319. // Add the bounce animation to the upper radius limit
  88320. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  88321. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  88322. }
  88323. });
  88324. };
  88325. BouncingBehavior.prototype.detach = function () {
  88326. if (!this._attachedCamera) {
  88327. return;
  88328. }
  88329. if (this._onAfterCheckInputsObserver) {
  88330. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88331. }
  88332. if (this._onMeshTargetChangedObserver) {
  88333. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88334. }
  88335. this._attachedCamera = null;
  88336. };
  88337. /**
  88338. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  88339. * @param radiusLimit The limit to check against.
  88340. * @return Bool to indicate if at limit.
  88341. */
  88342. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  88343. if (!this._attachedCamera) {
  88344. return false;
  88345. }
  88346. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  88347. return true;
  88348. }
  88349. return false;
  88350. };
  88351. /**
  88352. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  88353. * @param radiusDelta The delta by which to animate to. Can be negative.
  88354. */
  88355. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  88356. var _this = this;
  88357. if (!this._attachedCamera) {
  88358. return;
  88359. }
  88360. if (!this._radiusBounceTransition) {
  88361. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  88362. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  88363. }
  88364. // Prevent zoom until bounce has completed
  88365. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  88366. this._attachedCamera.wheelPrecision = Infinity;
  88367. this._attachedCamera.inertialRadiusOffset = 0;
  88368. // Animate to the radius limit
  88369. this.stopAllAnimations();
  88370. this._radiusIsAnimating = true;
  88371. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  88372. if (animatable) {
  88373. this._animatables.push(animatable);
  88374. }
  88375. };
  88376. /**
  88377. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  88378. */
  88379. BouncingBehavior.prototype._clearAnimationLocks = function () {
  88380. this._radiusIsAnimating = false;
  88381. if (this._attachedCamera) {
  88382. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  88383. }
  88384. };
  88385. /**
  88386. * Stops and removes all animations that have been applied to the camera
  88387. */
  88388. BouncingBehavior.prototype.stopAllAnimations = function () {
  88389. if (this._attachedCamera) {
  88390. this._attachedCamera.animations = [];
  88391. }
  88392. while (this._animatables.length) {
  88393. this._animatables[0].onAnimationEnd = null;
  88394. this._animatables[0].stop();
  88395. this._animatables.shift();
  88396. }
  88397. };
  88398. /**
  88399. * The easing function used by animations
  88400. */
  88401. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  88402. /**
  88403. * The easing mode used by animations
  88404. */
  88405. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  88406. return BouncingBehavior;
  88407. }());
  88408. BABYLON.BouncingBehavior = BouncingBehavior;
  88409. })(BABYLON || (BABYLON = {}));
  88410. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  88411. var BABYLON;
  88412. (function (BABYLON) {
  88413. var AutoRotationBehavior = /** @class */ (function () {
  88414. function AutoRotationBehavior() {
  88415. this._zoomStopsAnimation = false;
  88416. this._idleRotationSpeed = 0.05;
  88417. this._idleRotationWaitTime = 2000;
  88418. this._idleRotationSpinupTime = 2000;
  88419. this._isPointerDown = false;
  88420. this._lastFrameTime = null;
  88421. this._lastInteractionTime = -Infinity;
  88422. this._cameraRotationSpeed = 0;
  88423. this._lastFrameRadius = 0;
  88424. }
  88425. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  88426. get: function () {
  88427. return "AutoRotation";
  88428. },
  88429. enumerable: true,
  88430. configurable: true
  88431. });
  88432. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  88433. /**
  88434. * Gets the flag that indicates if user zooming should stop animation.
  88435. */
  88436. get: function () {
  88437. return this._zoomStopsAnimation;
  88438. },
  88439. /**
  88440. * Sets the flag that indicates if user zooming should stop animation.
  88441. */
  88442. set: function (flag) {
  88443. this._zoomStopsAnimation = flag;
  88444. },
  88445. enumerable: true,
  88446. configurable: true
  88447. });
  88448. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  88449. /**
  88450. * Gets the default speed at which the camera rotates around the model.
  88451. */
  88452. get: function () {
  88453. return this._idleRotationSpeed;
  88454. },
  88455. /**
  88456. * Sets the default speed at which the camera rotates around the model.
  88457. */
  88458. set: function (speed) {
  88459. this._idleRotationSpeed = speed;
  88460. },
  88461. enumerable: true,
  88462. configurable: true
  88463. });
  88464. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  88465. /**
  88466. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  88467. */
  88468. get: function () {
  88469. return this._idleRotationWaitTime;
  88470. },
  88471. /**
  88472. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  88473. */
  88474. set: function (time) {
  88475. this._idleRotationWaitTime = time;
  88476. },
  88477. enumerable: true,
  88478. configurable: true
  88479. });
  88480. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  88481. /**
  88482. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88483. */
  88484. get: function () {
  88485. return this._idleRotationSpinupTime;
  88486. },
  88487. /**
  88488. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88489. */
  88490. set: function (time) {
  88491. this._idleRotationSpinupTime = time;
  88492. },
  88493. enumerable: true,
  88494. configurable: true
  88495. });
  88496. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  88497. /**
  88498. * Gets a value indicating if the camera is currently rotating because of this behavior
  88499. */
  88500. get: function () {
  88501. return Math.abs(this._cameraRotationSpeed) > 0;
  88502. },
  88503. enumerable: true,
  88504. configurable: true
  88505. });
  88506. AutoRotationBehavior.prototype.init = function () {
  88507. // Do notihng
  88508. };
  88509. AutoRotationBehavior.prototype.attach = function (camera) {
  88510. var _this = this;
  88511. this._attachedCamera = camera;
  88512. var scene = this._attachedCamera.getScene();
  88513. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88514. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88515. _this._isPointerDown = true;
  88516. return;
  88517. }
  88518. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88519. _this._isPointerDown = false;
  88520. }
  88521. });
  88522. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88523. var now = BABYLON.Tools.Now;
  88524. var dt = 0;
  88525. if (_this._lastFrameTime != null) {
  88526. dt = now - _this._lastFrameTime;
  88527. }
  88528. _this._lastFrameTime = now;
  88529. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88530. _this._applyUserInteraction();
  88531. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  88532. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  88533. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  88534. // Step camera rotation by rotation speed
  88535. if (_this._attachedCamera) {
  88536. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  88537. }
  88538. });
  88539. };
  88540. AutoRotationBehavior.prototype.detach = function () {
  88541. if (!this._attachedCamera) {
  88542. return;
  88543. }
  88544. var scene = this._attachedCamera.getScene();
  88545. if (this._onPrePointerObservableObserver) {
  88546. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88547. }
  88548. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88549. this._attachedCamera = null;
  88550. };
  88551. /**
  88552. * Returns true if user is scrolling.
  88553. * @return true if user is scrolling.
  88554. */
  88555. AutoRotationBehavior.prototype._userIsZooming = function () {
  88556. if (!this._attachedCamera) {
  88557. return false;
  88558. }
  88559. return this._attachedCamera.inertialRadiusOffset !== 0;
  88560. };
  88561. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  88562. if (!this._attachedCamera) {
  88563. return false;
  88564. }
  88565. var zoomHasHitLimit = false;
  88566. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  88567. zoomHasHitLimit = true;
  88568. }
  88569. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  88570. this._lastFrameRadius = this._attachedCamera.radius;
  88571. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  88572. };
  88573. /**
  88574. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88575. */
  88576. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  88577. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  88578. this._lastInteractionTime = BABYLON.Tools.Now;
  88579. }
  88580. };
  88581. // Tools
  88582. AutoRotationBehavior.prototype._userIsMoving = function () {
  88583. if (!this._attachedCamera) {
  88584. return false;
  88585. }
  88586. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88587. this._attachedCamera.inertialBetaOffset !== 0 ||
  88588. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88589. this._attachedCamera.inertialPanningX !== 0 ||
  88590. this._attachedCamera.inertialPanningY !== 0 ||
  88591. this._isPointerDown;
  88592. };
  88593. return AutoRotationBehavior;
  88594. }());
  88595. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  88596. })(BABYLON || (BABYLON = {}));
  88597. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  88598. var BABYLON;
  88599. (function (BABYLON) {
  88600. var NullEngineOptions = /** @class */ (function () {
  88601. function NullEngineOptions() {
  88602. this.renderWidth = 512;
  88603. this.renderHeight = 256;
  88604. this.textureSize = 512;
  88605. this.deterministicLockstep = false;
  88606. this.lockstepMaxSteps = 4;
  88607. }
  88608. return NullEngineOptions;
  88609. }());
  88610. BABYLON.NullEngineOptions = NullEngineOptions;
  88611. /**
  88612. * The null engine class provides support for headless version of babylon.js.
  88613. * This can be used in server side scenario or for testing purposes
  88614. */
  88615. var NullEngine = /** @class */ (function (_super) {
  88616. __extends(NullEngine, _super);
  88617. function NullEngine(options) {
  88618. if (options === void 0) { options = new NullEngineOptions(); }
  88619. var _this = _super.call(this, null) || this;
  88620. if (options.deterministicLockstep === undefined) {
  88621. options.deterministicLockstep = false;
  88622. }
  88623. if (options.lockstepMaxSteps === undefined) {
  88624. options.lockstepMaxSteps = 4;
  88625. }
  88626. _this._options = options;
  88627. // Init caps
  88628. // We consider we are on a webgl1 capable device
  88629. _this._caps = new BABYLON.EngineCapabilities();
  88630. _this._caps.maxTexturesImageUnits = 16;
  88631. _this._caps.maxVertexTextureImageUnits = 16;
  88632. _this._caps.maxTextureSize = 512;
  88633. _this._caps.maxCubemapTextureSize = 512;
  88634. _this._caps.maxRenderTextureSize = 512;
  88635. _this._caps.maxVertexAttribs = 16;
  88636. _this._caps.maxVaryingVectors = 16;
  88637. _this._caps.maxFragmentUniformVectors = 16;
  88638. _this._caps.maxVertexUniformVectors = 16;
  88639. // Extensions
  88640. _this._caps.standardDerivatives = false;
  88641. _this._caps.astc = null;
  88642. _this._caps.s3tc = null;
  88643. _this._caps.pvrtc = null;
  88644. _this._caps.etc1 = null;
  88645. _this._caps.etc2 = null;
  88646. _this._caps.textureAnisotropicFilterExtension = null;
  88647. _this._caps.maxAnisotropy = 0;
  88648. _this._caps.uintIndices = false;
  88649. _this._caps.fragmentDepthSupported = false;
  88650. _this._caps.highPrecisionShaderSupported = true;
  88651. _this._caps.colorBufferFloat = false;
  88652. _this._caps.textureFloat = false;
  88653. _this._caps.textureFloatLinearFiltering = false;
  88654. _this._caps.textureFloatRender = false;
  88655. _this._caps.textureHalfFloat = false;
  88656. _this._caps.textureHalfFloatLinearFiltering = false;
  88657. _this._caps.textureHalfFloatRender = false;
  88658. _this._caps.textureLOD = false;
  88659. _this._caps.drawBuffersExtension = false;
  88660. _this._caps.depthTextureExtension = false;
  88661. _this._caps.vertexArrayObject = false;
  88662. _this._caps.instancedArrays = false;
  88663. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  88664. // Wrappers
  88665. if (typeof URL === "undefined") {
  88666. URL = {
  88667. createObjectURL: function () { },
  88668. revokeObjectURL: function () { }
  88669. };
  88670. }
  88671. if (typeof Blob === "undefined") {
  88672. Blob = function () { };
  88673. }
  88674. return _this;
  88675. }
  88676. NullEngine.prototype.isDeterministicLockStep = function () {
  88677. return this._options.deterministicLockstep;
  88678. };
  88679. NullEngine.prototype.getLockstepMaxSteps = function () {
  88680. return this._options.lockstepMaxSteps;
  88681. };
  88682. NullEngine.prototype.getHardwareScalingLevel = function () {
  88683. return 1.0;
  88684. };
  88685. NullEngine.prototype.createVertexBuffer = function (vertices) {
  88686. return {
  88687. capacity: 0,
  88688. references: 1,
  88689. is32Bits: false
  88690. };
  88691. };
  88692. NullEngine.prototype.createIndexBuffer = function (indices) {
  88693. return {
  88694. capacity: 0,
  88695. references: 1,
  88696. is32Bits: false
  88697. };
  88698. };
  88699. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  88700. if (stencil === void 0) { stencil = false; }
  88701. };
  88702. NullEngine.prototype.getRenderWidth = function (useScreen) {
  88703. if (useScreen === void 0) { useScreen = false; }
  88704. if (!useScreen && this._currentRenderTarget) {
  88705. return this._currentRenderTarget.width;
  88706. }
  88707. return this._options.renderWidth;
  88708. };
  88709. NullEngine.prototype.getRenderHeight = function (useScreen) {
  88710. if (useScreen === void 0) { useScreen = false; }
  88711. if (!useScreen && this._currentRenderTarget) {
  88712. return this._currentRenderTarget.height;
  88713. }
  88714. return this._options.renderHeight;
  88715. };
  88716. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  88717. this._cachedViewport = viewport;
  88718. };
  88719. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  88720. return {
  88721. transformFeedback: null,
  88722. __SPECTOR_rebuildProgram: null
  88723. };
  88724. };
  88725. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  88726. return [];
  88727. };
  88728. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  88729. return [];
  88730. };
  88731. NullEngine.prototype.bindSamplers = function (effect) {
  88732. this._currentEffect = null;
  88733. };
  88734. NullEngine.prototype.enableEffect = function (effect) {
  88735. this._currentEffect = effect;
  88736. if (effect.onBind) {
  88737. effect.onBind(effect);
  88738. }
  88739. effect.onBindObservable.notifyObservers(effect);
  88740. };
  88741. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  88742. if (zOffset === void 0) { zOffset = 0; }
  88743. if (reverseSide === void 0) { reverseSide = false; }
  88744. };
  88745. NullEngine.prototype.setIntArray = function (uniform, array) {
  88746. };
  88747. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  88748. };
  88749. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  88750. };
  88751. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  88752. };
  88753. NullEngine.prototype.setFloatArray = function (uniform, array) {
  88754. };
  88755. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  88756. };
  88757. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  88758. };
  88759. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  88760. };
  88761. NullEngine.prototype.setArray = function (uniform, array) {
  88762. };
  88763. NullEngine.prototype.setArray2 = function (uniform, array) {
  88764. };
  88765. NullEngine.prototype.setArray3 = function (uniform, array) {
  88766. };
  88767. NullEngine.prototype.setArray4 = function (uniform, array) {
  88768. };
  88769. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  88770. };
  88771. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  88772. };
  88773. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  88774. };
  88775. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  88776. };
  88777. NullEngine.prototype.setFloat = function (uniform, value) {
  88778. };
  88779. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  88780. };
  88781. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  88782. };
  88783. NullEngine.prototype.setBool = function (uniform, bool) {
  88784. };
  88785. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  88786. };
  88787. NullEngine.prototype.setColor3 = function (uniform, color3) {
  88788. };
  88789. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  88790. };
  88791. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  88792. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  88793. if (this._alphaMode === mode) {
  88794. return;
  88795. }
  88796. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  88797. if (!noDepthWriteChange) {
  88798. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  88799. }
  88800. this._alphaMode = mode;
  88801. };
  88802. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  88803. };
  88804. NullEngine.prototype.wipeCaches = function (bruteForce) {
  88805. if (this.preventCacheWipeBetweenFrames) {
  88806. return;
  88807. }
  88808. this.resetTextureCache();
  88809. this._currentEffect = null;
  88810. if (bruteForce) {
  88811. this._currentProgram = null;
  88812. this._stencilState.reset();
  88813. this._depthCullingState.reset();
  88814. this._alphaState.reset();
  88815. }
  88816. this._cachedVertexBuffers = null;
  88817. this._cachedIndexBuffer = null;
  88818. this._cachedEffectForVertexBuffers = null;
  88819. };
  88820. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  88821. };
  88822. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  88823. };
  88824. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  88825. };
  88826. NullEngine.prototype._createTexture = function () {
  88827. return {};
  88828. };
  88829. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  88830. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88831. if (onLoad === void 0) { onLoad = null; }
  88832. if (onError === void 0) { onError = null; }
  88833. if (buffer === void 0) { buffer = null; }
  88834. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  88835. var url = String(urlArg);
  88836. texture.url = url;
  88837. texture.generateMipMaps = !noMipmap;
  88838. texture.samplingMode = samplingMode;
  88839. texture.invertY = invertY;
  88840. texture.baseWidth = this._options.textureSize;
  88841. texture.baseHeight = this._options.textureSize;
  88842. texture.width = this._options.textureSize;
  88843. texture.height = this._options.textureSize;
  88844. if (format) {
  88845. texture.format = format;
  88846. }
  88847. texture.isReady = true;
  88848. if (onLoad) {
  88849. onLoad();
  88850. }
  88851. return texture;
  88852. };
  88853. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  88854. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  88855. if (options !== undefined && typeof options === "object") {
  88856. fullOptions.generateMipMaps = options.generateMipMaps;
  88857. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  88858. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  88859. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  88860. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  88861. }
  88862. else {
  88863. fullOptions.generateMipMaps = options;
  88864. fullOptions.generateDepthBuffer = true;
  88865. fullOptions.generateStencilBuffer = false;
  88866. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88867. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  88868. }
  88869. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  88870. var width = size.width || size;
  88871. var height = size.height || size;
  88872. texture._depthStencilBuffer = {};
  88873. texture._framebuffer = {};
  88874. texture.baseWidth = width;
  88875. texture.baseHeight = height;
  88876. texture.width = width;
  88877. texture.height = height;
  88878. texture.isReady = true;
  88879. texture.samples = 1;
  88880. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  88881. texture.samplingMode = fullOptions.samplingMode;
  88882. texture.type = fullOptions.type;
  88883. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  88884. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  88885. return texture;
  88886. };
  88887. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  88888. texture.samplingMode = samplingMode;
  88889. };
  88890. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  88891. if (this._currentRenderTarget) {
  88892. this.unBindFramebuffer(this._currentRenderTarget);
  88893. }
  88894. this._currentRenderTarget = texture;
  88895. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  88896. if (this._cachedViewport && !forceFullscreenViewport) {
  88897. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  88898. }
  88899. };
  88900. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  88901. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  88902. this._currentRenderTarget = null;
  88903. if (onBeforeUnbind) {
  88904. if (texture._MSAAFramebuffer) {
  88905. this._currentFramebuffer = texture._framebuffer;
  88906. }
  88907. onBeforeUnbind();
  88908. }
  88909. this._currentFramebuffer = null;
  88910. };
  88911. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  88912. var vbo = {
  88913. capacity: 1,
  88914. references: 1,
  88915. is32Bits: false
  88916. };
  88917. return vbo;
  88918. };
  88919. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  88920. if (offset === void 0) { offset = 0; }
  88921. };
  88922. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  88923. };
  88924. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  88925. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  88926. this._boundTexturesCache[this._activeChannel] = texture;
  88927. }
  88928. };
  88929. NullEngine.prototype._bindTexture = function (channel, texture) {
  88930. if (channel < 0) {
  88931. return;
  88932. }
  88933. this._bindTextureDirectly(0, texture);
  88934. };
  88935. NullEngine.prototype._releaseBuffer = function (buffer) {
  88936. buffer.references--;
  88937. if (buffer.references === 0) {
  88938. return true;
  88939. }
  88940. return false;
  88941. };
  88942. return NullEngine;
  88943. }(BABYLON.Engine));
  88944. BABYLON.NullEngine = NullEngine;
  88945. })(BABYLON || (BABYLON = {}));
  88946. //# sourceMappingURL=babylon.nullEngine.js.map
  88947. var BABYLON;
  88948. (function (BABYLON) {
  88949. /**
  88950. * This class can be used to get instrumentation data from a Babylon engine
  88951. */
  88952. var EngineInstrumentation = /** @class */ (function () {
  88953. function EngineInstrumentation(engine) {
  88954. this.engine = engine;
  88955. this._captureGPUFrameTime = false;
  88956. this._gpuFrameTime = new BABYLON.PerfCounter();
  88957. this._captureShaderCompilationTime = false;
  88958. this._shaderCompilationTime = new BABYLON.PerfCounter();
  88959. // Observers
  88960. this._onBeginFrameObserver = null;
  88961. this._onEndFrameObserver = null;
  88962. this._onBeforeShaderCompilationObserver = null;
  88963. this._onAfterShaderCompilationObserver = null;
  88964. }
  88965. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  88966. // Properties
  88967. /**
  88968. * Gets the perf counter used for GPU frame time
  88969. */
  88970. get: function () {
  88971. return this._gpuFrameTime;
  88972. },
  88973. enumerable: true,
  88974. configurable: true
  88975. });
  88976. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  88977. /**
  88978. * Gets the GPU frame time capture status
  88979. */
  88980. get: function () {
  88981. return this._captureGPUFrameTime;
  88982. },
  88983. /**
  88984. * Enable or disable the GPU frame time capture
  88985. */
  88986. set: function (value) {
  88987. var _this = this;
  88988. if (value === this._captureGPUFrameTime) {
  88989. return;
  88990. }
  88991. this._captureGPUFrameTime = value;
  88992. if (value) {
  88993. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  88994. if (!_this._gpuFrameTimeToken) {
  88995. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  88996. }
  88997. });
  88998. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  88999. if (!_this._gpuFrameTimeToken) {
  89000. return;
  89001. }
  89002. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  89003. if (time > -1) {
  89004. _this._gpuFrameTimeToken = null;
  89005. _this._gpuFrameTime.fetchNewFrame();
  89006. _this._gpuFrameTime.addCount(time, true);
  89007. }
  89008. });
  89009. }
  89010. else {
  89011. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89012. this._onBeginFrameObserver = null;
  89013. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89014. this._onEndFrameObserver = null;
  89015. }
  89016. },
  89017. enumerable: true,
  89018. configurable: true
  89019. });
  89020. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  89021. /**
  89022. * Gets the perf counter used for shader compilation time
  89023. */
  89024. get: function () {
  89025. return this._shaderCompilationTime;
  89026. },
  89027. enumerable: true,
  89028. configurable: true
  89029. });
  89030. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  89031. /**
  89032. * Gets the shader compilation time capture status
  89033. */
  89034. get: function () {
  89035. return this._captureShaderCompilationTime;
  89036. },
  89037. /**
  89038. * Enable or disable the shader compilation time capture
  89039. */
  89040. set: function (value) {
  89041. var _this = this;
  89042. if (value === this._captureShaderCompilationTime) {
  89043. return;
  89044. }
  89045. this._captureShaderCompilationTime = value;
  89046. if (value) {
  89047. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  89048. _this._shaderCompilationTime.fetchNewFrame();
  89049. _this._shaderCompilationTime.beginMonitoring();
  89050. });
  89051. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  89052. _this._shaderCompilationTime.endMonitoring();
  89053. });
  89054. }
  89055. else {
  89056. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89057. this._onBeforeShaderCompilationObserver = null;
  89058. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89059. this._onAfterShaderCompilationObserver = null;
  89060. }
  89061. },
  89062. enumerable: true,
  89063. configurable: true
  89064. });
  89065. EngineInstrumentation.prototype.dispose = function () {
  89066. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89067. this._onBeginFrameObserver = null;
  89068. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89069. this._onEndFrameObserver = null;
  89070. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89071. this._onBeforeShaderCompilationObserver = null;
  89072. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89073. this._onAfterShaderCompilationObserver = null;
  89074. this.engine = null;
  89075. };
  89076. return EngineInstrumentation;
  89077. }());
  89078. BABYLON.EngineInstrumentation = EngineInstrumentation;
  89079. })(BABYLON || (BABYLON = {}));
  89080. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  89081. var BABYLON;
  89082. (function (BABYLON) {
  89083. /**
  89084. * This class can be used to get instrumentation data from a Babylon engine
  89085. */
  89086. var SceneInstrumentation = /** @class */ (function () {
  89087. function SceneInstrumentation(scene) {
  89088. var _this = this;
  89089. this.scene = scene;
  89090. this._captureActiveMeshesEvaluationTime = false;
  89091. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  89092. this._captureRenderTargetsRenderTime = false;
  89093. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  89094. this._captureFrameTime = false;
  89095. this._frameTime = new BABYLON.PerfCounter();
  89096. this._captureRenderTime = false;
  89097. this._renderTime = new BABYLON.PerfCounter();
  89098. this._captureInterFrameTime = false;
  89099. this._interFrameTime = new BABYLON.PerfCounter();
  89100. this._captureParticlesRenderTime = false;
  89101. this._particlesRenderTime = new BABYLON.PerfCounter();
  89102. this._captureSpritesRenderTime = false;
  89103. this._spritesRenderTime = new BABYLON.PerfCounter();
  89104. this._capturePhysicsTime = false;
  89105. this._physicsTime = new BABYLON.PerfCounter();
  89106. this._captureAnimationsTime = false;
  89107. this._animationsTime = new BABYLON.PerfCounter();
  89108. // Observers
  89109. this._onBeforeActiveMeshesEvaluationObserver = null;
  89110. this._onAfterActiveMeshesEvaluationObserver = null;
  89111. this._onBeforeRenderTargetsRenderObserver = null;
  89112. this._onAfterRenderTargetsRenderObserver = null;
  89113. this._onAfterRenderObserver = null;
  89114. this._onBeforeDrawPhaseObserver = null;
  89115. this._onAfterDrawPhaseObserver = null;
  89116. this._onBeforeAnimationsObserver = null;
  89117. this._onBeforeParticlesRenderingObserver = null;
  89118. this._onAfterParticlesRenderingObserver = null;
  89119. this._onBeforeSpritesRenderingObserver = null;
  89120. this._onAfterSpritesRenderingObserver = null;
  89121. this._onBeforePhysicsObserver = null;
  89122. this._onAfterPhysicsObserver = null;
  89123. this._onAfterAnimationsObserver = null;
  89124. // Before render
  89125. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  89126. if (_this._captureActiveMeshesEvaluationTime) {
  89127. _this._activeMeshesEvaluationTime.fetchNewFrame();
  89128. }
  89129. if (_this._captureRenderTargetsRenderTime) {
  89130. _this._renderTargetsRenderTime.fetchNewFrame();
  89131. }
  89132. if (_this._captureFrameTime) {
  89133. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  89134. _this._frameTime.beginMonitoring();
  89135. }
  89136. if (_this._captureInterFrameTime) {
  89137. _this._interFrameTime.endMonitoring();
  89138. }
  89139. if (_this._captureParticlesRenderTime) {
  89140. _this._particlesRenderTime.fetchNewFrame();
  89141. }
  89142. if (_this._captureSpritesRenderTime) {
  89143. _this._spritesRenderTime.fetchNewFrame();
  89144. }
  89145. if (_this._captureAnimationsTime) {
  89146. _this._animationsTime.beginMonitoring();
  89147. }
  89148. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  89149. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  89150. });
  89151. // After render
  89152. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  89153. if (_this._captureFrameTime) {
  89154. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  89155. _this._frameTime.endMonitoring();
  89156. }
  89157. if (_this._captureRenderTime) {
  89158. _this._renderTime.endMonitoring(false);
  89159. }
  89160. if (_this._captureInterFrameTime) {
  89161. _this._interFrameTime.beginMonitoring();
  89162. }
  89163. });
  89164. }
  89165. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  89166. // Properties
  89167. /**
  89168. * Gets the perf counter used for active meshes evaluation time
  89169. */
  89170. get: function () {
  89171. return this._activeMeshesEvaluationTime;
  89172. },
  89173. enumerable: true,
  89174. configurable: true
  89175. });
  89176. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  89177. /**
  89178. * Gets the active meshes evaluation time capture status
  89179. */
  89180. get: function () {
  89181. return this._captureActiveMeshesEvaluationTime;
  89182. },
  89183. /**
  89184. * Enable or disable the active meshes evaluation time capture
  89185. */
  89186. set: function (value) {
  89187. var _this = this;
  89188. if (value === this._captureActiveMeshesEvaluationTime) {
  89189. return;
  89190. }
  89191. this._captureActiveMeshesEvaluationTime = value;
  89192. if (value) {
  89193. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  89194. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  89195. _this._activeMeshesEvaluationTime.beginMonitoring();
  89196. });
  89197. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  89198. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  89199. _this._activeMeshesEvaluationTime.endMonitoring();
  89200. });
  89201. }
  89202. else {
  89203. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89204. this._onBeforeActiveMeshesEvaluationObserver = null;
  89205. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89206. this._onAfterActiveMeshesEvaluationObserver = null;
  89207. }
  89208. },
  89209. enumerable: true,
  89210. configurable: true
  89211. });
  89212. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  89213. /**
  89214. * Gets the perf counter used for render targets render time
  89215. */
  89216. get: function () {
  89217. return this._renderTargetsRenderTime;
  89218. },
  89219. enumerable: true,
  89220. configurable: true
  89221. });
  89222. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  89223. /**
  89224. * Gets the render targets render time capture status
  89225. */
  89226. get: function () {
  89227. return this._captureRenderTargetsRenderTime;
  89228. },
  89229. /**
  89230. * Enable or disable the render targets render time capture
  89231. */
  89232. set: function (value) {
  89233. var _this = this;
  89234. if (value === this._captureRenderTargetsRenderTime) {
  89235. return;
  89236. }
  89237. this._captureRenderTargetsRenderTime = value;
  89238. if (value) {
  89239. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  89240. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  89241. _this._renderTargetsRenderTime.beginMonitoring();
  89242. });
  89243. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  89244. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  89245. _this._renderTargetsRenderTime.endMonitoring(false);
  89246. });
  89247. }
  89248. else {
  89249. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89250. this._onBeforeRenderTargetsRenderObserver = null;
  89251. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89252. this._onAfterRenderTargetsRenderObserver = null;
  89253. }
  89254. },
  89255. enumerable: true,
  89256. configurable: true
  89257. });
  89258. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  89259. /**
  89260. * Gets the perf counter used for particles render time
  89261. */
  89262. get: function () {
  89263. return this._particlesRenderTime;
  89264. },
  89265. enumerable: true,
  89266. configurable: true
  89267. });
  89268. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  89269. /**
  89270. * Gets the particles render time capture status
  89271. */
  89272. get: function () {
  89273. return this._captureParticlesRenderTime;
  89274. },
  89275. /**
  89276. * Enable or disable the particles render time capture
  89277. */
  89278. set: function (value) {
  89279. var _this = this;
  89280. if (value === this._captureParticlesRenderTime) {
  89281. return;
  89282. }
  89283. this._captureParticlesRenderTime = value;
  89284. if (value) {
  89285. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  89286. BABYLON.Tools.StartPerformanceCounter("Particles");
  89287. _this._particlesRenderTime.beginMonitoring();
  89288. });
  89289. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  89290. BABYLON.Tools.EndPerformanceCounter("Particles");
  89291. _this._particlesRenderTime.endMonitoring(false);
  89292. });
  89293. }
  89294. else {
  89295. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89296. this._onBeforeParticlesRenderingObserver = null;
  89297. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89298. this._onAfterParticlesRenderingObserver = null;
  89299. }
  89300. },
  89301. enumerable: true,
  89302. configurable: true
  89303. });
  89304. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  89305. /**
  89306. * Gets the perf counter used for sprites render time
  89307. */
  89308. get: function () {
  89309. return this._spritesRenderTime;
  89310. },
  89311. enumerable: true,
  89312. configurable: true
  89313. });
  89314. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  89315. /**
  89316. * Gets the sprites render time capture status
  89317. */
  89318. get: function () {
  89319. return this._captureSpritesRenderTime;
  89320. },
  89321. /**
  89322. * Enable or disable the sprites render time capture
  89323. */
  89324. set: function (value) {
  89325. var _this = this;
  89326. if (value === this._captureSpritesRenderTime) {
  89327. return;
  89328. }
  89329. this._captureSpritesRenderTime = value;
  89330. if (value) {
  89331. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  89332. BABYLON.Tools.StartPerformanceCounter("Sprites");
  89333. _this._spritesRenderTime.beginMonitoring();
  89334. });
  89335. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  89336. BABYLON.Tools.EndPerformanceCounter("Sprites");
  89337. _this._spritesRenderTime.endMonitoring(false);
  89338. });
  89339. }
  89340. else {
  89341. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89342. this._onBeforeSpritesRenderingObserver = null;
  89343. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89344. this._onAfterSpritesRenderingObserver = null;
  89345. }
  89346. },
  89347. enumerable: true,
  89348. configurable: true
  89349. });
  89350. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  89351. /**
  89352. * Gets the perf counter used for physics time
  89353. */
  89354. get: function () {
  89355. return this._physicsTime;
  89356. },
  89357. enumerable: true,
  89358. configurable: true
  89359. });
  89360. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  89361. /**
  89362. * Gets the physics time capture status
  89363. */
  89364. get: function () {
  89365. return this._capturePhysicsTime;
  89366. },
  89367. /**
  89368. * Enable or disable the physics time capture
  89369. */
  89370. set: function (value) {
  89371. var _this = this;
  89372. if (value === this._capturePhysicsTime) {
  89373. return;
  89374. }
  89375. this._capturePhysicsTime = value;
  89376. if (value) {
  89377. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  89378. BABYLON.Tools.StartPerformanceCounter("Physics");
  89379. _this._physicsTime.beginMonitoring();
  89380. });
  89381. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  89382. BABYLON.Tools.EndPerformanceCounter("Physics");
  89383. _this._physicsTime.endMonitoring();
  89384. });
  89385. }
  89386. else {
  89387. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89388. this._onBeforePhysicsObserver = null;
  89389. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89390. this._onAfterPhysicsObserver = null;
  89391. }
  89392. },
  89393. enumerable: true,
  89394. configurable: true
  89395. });
  89396. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  89397. /**
  89398. * Gets the perf counter used for animations time
  89399. */
  89400. get: function () {
  89401. return this._animationsTime;
  89402. },
  89403. enumerable: true,
  89404. configurable: true
  89405. });
  89406. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  89407. /**
  89408. * Gets the animations time capture status
  89409. */
  89410. get: function () {
  89411. return this._captureAnimationsTime;
  89412. },
  89413. /**
  89414. * Enable or disable the animations time capture
  89415. */
  89416. set: function (value) {
  89417. var _this = this;
  89418. if (value === this._captureAnimationsTime) {
  89419. return;
  89420. }
  89421. this._captureAnimationsTime = value;
  89422. if (value) {
  89423. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  89424. _this._animationsTime.endMonitoring();
  89425. });
  89426. }
  89427. else {
  89428. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89429. this._onAfterAnimationsObserver = null;
  89430. }
  89431. },
  89432. enumerable: true,
  89433. configurable: true
  89434. });
  89435. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  89436. /**
  89437. * Gets the perf counter used for frame time capture
  89438. */
  89439. get: function () {
  89440. return this._frameTime;
  89441. },
  89442. enumerable: true,
  89443. configurable: true
  89444. });
  89445. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  89446. /**
  89447. * Gets the frame time capture status
  89448. */
  89449. get: function () {
  89450. return this._captureFrameTime;
  89451. },
  89452. /**
  89453. * Enable or disable the frame time capture
  89454. */
  89455. set: function (value) {
  89456. this._captureFrameTime = value;
  89457. },
  89458. enumerable: true,
  89459. configurable: true
  89460. });
  89461. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  89462. /**
  89463. * Gets the perf counter used for inter-frames time capture
  89464. */
  89465. get: function () {
  89466. return this._interFrameTime;
  89467. },
  89468. enumerable: true,
  89469. configurable: true
  89470. });
  89471. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  89472. /**
  89473. * Gets the inter-frames time capture status
  89474. */
  89475. get: function () {
  89476. return this._captureInterFrameTime;
  89477. },
  89478. /**
  89479. * Enable or disable the inter-frames time capture
  89480. */
  89481. set: function (value) {
  89482. this._captureInterFrameTime = value;
  89483. },
  89484. enumerable: true,
  89485. configurable: true
  89486. });
  89487. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  89488. /**
  89489. * Gets the perf counter used for render time capture
  89490. */
  89491. get: function () {
  89492. return this._renderTime;
  89493. },
  89494. enumerable: true,
  89495. configurable: true
  89496. });
  89497. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  89498. /**
  89499. * Gets the render time capture status
  89500. */
  89501. get: function () {
  89502. return this._captureRenderTime;
  89503. },
  89504. /**
  89505. * Enable or disable the render time capture
  89506. */
  89507. set: function (value) {
  89508. var _this = this;
  89509. if (value === this._captureRenderTime) {
  89510. return;
  89511. }
  89512. this._captureRenderTime = value;
  89513. if (value) {
  89514. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  89515. _this._renderTime.beginMonitoring();
  89516. BABYLON.Tools.StartPerformanceCounter("Main render");
  89517. });
  89518. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  89519. _this._renderTime.endMonitoring(false);
  89520. BABYLON.Tools.EndPerformanceCounter("Main render");
  89521. });
  89522. }
  89523. else {
  89524. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89525. this._onBeforeDrawPhaseObserver = null;
  89526. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89527. this._onAfterDrawPhaseObserver = null;
  89528. }
  89529. },
  89530. enumerable: true,
  89531. configurable: true
  89532. });
  89533. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  89534. /**
  89535. * Gets the perf counter used for draw calls
  89536. */
  89537. get: function () {
  89538. return this.scene.getEngine()._drawCalls;
  89539. },
  89540. enumerable: true,
  89541. configurable: true
  89542. });
  89543. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  89544. /**
  89545. * Gets the perf counter used for texture collisions
  89546. */
  89547. get: function () {
  89548. return this.scene.getEngine()._textureCollisions;
  89549. },
  89550. enumerable: true,
  89551. configurable: true
  89552. });
  89553. SceneInstrumentation.prototype.dispose = function () {
  89554. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89555. this._onAfterRenderObserver = null;
  89556. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89557. this._onBeforeActiveMeshesEvaluationObserver = null;
  89558. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89559. this._onAfterActiveMeshesEvaluationObserver = null;
  89560. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89561. this._onBeforeRenderTargetsRenderObserver = null;
  89562. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89563. this._onAfterRenderTargetsRenderObserver = null;
  89564. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  89565. this._onBeforeAnimationsObserver = null;
  89566. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89567. this._onBeforeParticlesRenderingObserver = null;
  89568. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89569. this._onAfterParticlesRenderingObserver = null;
  89570. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89571. this._onBeforeSpritesRenderingObserver = null;
  89572. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89573. this._onAfterSpritesRenderingObserver = null;
  89574. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89575. this._onBeforeDrawPhaseObserver = null;
  89576. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89577. this._onAfterDrawPhaseObserver = null;
  89578. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89579. this._onBeforePhysicsObserver = null;
  89580. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89581. this._onAfterPhysicsObserver = null;
  89582. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89583. this._onAfterAnimationsObserver = null;
  89584. this.scene = null;
  89585. };
  89586. return SceneInstrumentation;
  89587. }());
  89588. BABYLON.SceneInstrumentation = SceneInstrumentation;
  89589. })(BABYLON || (BABYLON = {}));
  89590. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  89591. var BABYLON;
  89592. (function (BABYLON) {
  89593. var _TimeToken = /** @class */ (function () {
  89594. function _TimeToken() {
  89595. this._timeElapsedQueryEnded = false;
  89596. }
  89597. return _TimeToken;
  89598. }());
  89599. BABYLON._TimeToken = _TimeToken;
  89600. })(BABYLON || (BABYLON = {}));
  89601. //# sourceMappingURL=babylon.timeToken.js.map
  89602. var BABYLON;
  89603. (function (BABYLON) {
  89604. /**
  89605. * Background material defines definition.
  89606. * @ignore Mainly internal Use
  89607. */
  89608. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  89609. __extends(BackgroundMaterialDefines, _super);
  89610. /**
  89611. * Constructor of the defines.
  89612. */
  89613. function BackgroundMaterialDefines() {
  89614. var _this = _super.call(this) || this;
  89615. /**
  89616. * True if the diffuse texture is in use.
  89617. */
  89618. _this.DIFFUSE = false;
  89619. /**
  89620. * The direct UV channel to use.
  89621. */
  89622. _this.DIFFUSEDIRECTUV = 0;
  89623. /**
  89624. * True if the diffuse texture is in gamma space.
  89625. */
  89626. _this.GAMMADIFFUSE = false;
  89627. /**
  89628. * True if the diffuse texture has opacity in the alpha channel.
  89629. */
  89630. _this.DIFFUSEHASALPHA = false;
  89631. /**
  89632. * True if you want the material to fade to transparent at grazing angle.
  89633. */
  89634. _this.OPACITYFRESNEL = false;
  89635. /**
  89636. * True if an extra blur needs to be added in the reflection.
  89637. */
  89638. _this.REFLECTIONBLUR = false;
  89639. /**
  89640. * True if you want the material to fade to reflection at grazing angle.
  89641. */
  89642. _this.REFLECTIONFRESNEL = false;
  89643. /**
  89644. * True if you want the material to falloff as far as you move away from the scene center.
  89645. */
  89646. _this.REFLECTIONFALLOFF = false;
  89647. /**
  89648. * False if the current Webgl implementation does not support the texture lod extension.
  89649. */
  89650. _this.TEXTURELODSUPPORT = false;
  89651. /**
  89652. * True to ensure the data are premultiplied.
  89653. */
  89654. _this.PREMULTIPLYALPHA = false;
  89655. /**
  89656. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  89657. */
  89658. _this.USERGBCOLOR = false;
  89659. /**
  89660. * True to add noise in order to reduce the banding effect.
  89661. */
  89662. _this.NOISE = false;
  89663. /**
  89664. * is the reflection texture in BGR color scheme?
  89665. * Mainly used to solve a bug in ios10 video tag
  89666. */
  89667. _this.REFLECTIONBGR = false;
  89668. _this.IMAGEPROCESSING = false;
  89669. _this.VIGNETTE = false;
  89670. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  89671. _this.VIGNETTEBLENDMODEOPAQUE = false;
  89672. _this.TONEMAPPING = false;
  89673. _this.CONTRAST = false;
  89674. _this.COLORCURVES = false;
  89675. _this.COLORGRADING = false;
  89676. _this.COLORGRADING3D = false;
  89677. _this.SAMPLER3DGREENDEPTH = false;
  89678. _this.SAMPLER3DBGRMAP = false;
  89679. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  89680. _this.EXPOSURE = false;
  89681. _this.GRAIN = false;
  89682. // Reflection.
  89683. _this.REFLECTION = false;
  89684. _this.REFLECTIONMAP_3D = false;
  89685. _this.REFLECTIONMAP_SPHERICAL = false;
  89686. _this.REFLECTIONMAP_PLANAR = false;
  89687. _this.REFLECTIONMAP_CUBIC = false;
  89688. _this.REFLECTIONMAP_PROJECTION = false;
  89689. _this.REFLECTIONMAP_SKYBOX = false;
  89690. _this.REFLECTIONMAP_EXPLICIT = false;
  89691. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89692. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89693. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89694. _this.INVERTCUBICMAP = false;
  89695. _this.REFLECTIONMAP_OPPOSITEZ = false;
  89696. _this.LODINREFLECTIONALPHA = false;
  89697. _this.GAMMAREFLECTION = false;
  89698. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  89699. // Default BJS.
  89700. _this.MAINUV1 = false;
  89701. _this.MAINUV2 = false;
  89702. _this.UV1 = false;
  89703. _this.UV2 = false;
  89704. _this.CLIPPLANE = false;
  89705. _this.POINTSIZE = false;
  89706. _this.FOG = false;
  89707. _this.NORMAL = false;
  89708. _this.NUM_BONE_INFLUENCERS = 0;
  89709. _this.BonesPerMesh = 0;
  89710. _this.INSTANCES = false;
  89711. _this.SHADOWFLOAT = false;
  89712. _this.rebuild();
  89713. return _this;
  89714. }
  89715. return BackgroundMaterialDefines;
  89716. }(BABYLON.MaterialDefines));
  89717. /**
  89718. * Background material used to create an efficient environement around your scene.
  89719. */
  89720. var BackgroundMaterial = /** @class */ (function (_super) {
  89721. __extends(BackgroundMaterial, _super);
  89722. /**
  89723. * Instantiates a Background Material in the given scene
  89724. * @param name The friendly name of the material
  89725. * @param scene The scene to add the material to
  89726. */
  89727. function BackgroundMaterial(name, scene) {
  89728. var _this = _super.call(this, name, scene) || this;
  89729. /**
  89730. * Key light Color (multiply against the R channel of the environement texture)
  89731. */
  89732. _this.primaryColor = BABYLON.Color3.White();
  89733. /**
  89734. * Key light Level (allowing HDR output of the background)
  89735. */
  89736. _this.primaryLevel = 1;
  89737. /**
  89738. * Secondary light Color (multiply against the G channel of the environement texture)
  89739. */
  89740. _this.secondaryColor = BABYLON.Color3.Gray();
  89741. /**
  89742. * Secondary light Level (allowing HDR output of the background)
  89743. */
  89744. _this.secondaryLevel = 1;
  89745. /**
  89746. * Tertiary light Color (multiply against the B channel of the environement texture)
  89747. */
  89748. _this.tertiaryColor = BABYLON.Color3.Black();
  89749. /**
  89750. * Tertiary light Level (allowing HDR output of the background)
  89751. */
  89752. _this.tertiaryLevel = 1;
  89753. /**
  89754. * Reflection Texture used in the material.
  89755. * Should be author in a specific way for the best result (refer to the documentation).
  89756. */
  89757. _this.reflectionTexture = null;
  89758. /**
  89759. * Reflection Texture level of blur.
  89760. *
  89761. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  89762. * texture twice.
  89763. */
  89764. _this.reflectionBlur = 0;
  89765. /**
  89766. * Diffuse Texture used in the material.
  89767. * Should be author in a specific way for the best result (refer to the documentation).
  89768. */
  89769. _this.diffuseTexture = null;
  89770. _this._shadowLights = null;
  89771. /**
  89772. * Specify the list of lights casting shadow on the material.
  89773. * All scene shadow lights will be included if null.
  89774. */
  89775. _this.shadowLights = null;
  89776. /**
  89777. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  89778. * soft lighting on the background.
  89779. */
  89780. _this.shadowBlurScale = 1;
  89781. /**
  89782. * Helps adjusting the shadow to a softer level if required.
  89783. * 0 means black shadows and 1 means no shadows.
  89784. */
  89785. _this.shadowLevel = 0;
  89786. /**
  89787. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  89788. * It is usually zero but might be interesting to modify according to your setup.
  89789. */
  89790. _this.sceneCenter = BABYLON.Vector3.Zero();
  89791. /**
  89792. * This helps specifying that the material is falling off to the sky box at grazing angle.
  89793. * This helps ensuring a nice transition when the camera goes under the ground.
  89794. */
  89795. _this.opacityFresnel = true;
  89796. /**
  89797. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  89798. * This helps adding a mirror texture on the ground.
  89799. */
  89800. _this.reflectionFresnel = false;
  89801. /**
  89802. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  89803. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  89804. */
  89805. _this.reflectionFalloffDistance = 0.0;
  89806. /**
  89807. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  89808. */
  89809. _this.reflectionAmount = 1.0;
  89810. /**
  89811. * This specifies the weight of the reflection at grazing angle.
  89812. */
  89813. _this.reflectionReflectance0 = 0.05;
  89814. /**
  89815. * This specifies the weight of the reflection at a perpendicular point of view.
  89816. */
  89817. _this.reflectionReflectance90 = 0.5;
  89818. /**
  89819. * Helps to directly use the maps channels instead of their level.
  89820. */
  89821. _this.useRGBColor = true;
  89822. /**
  89823. * This helps reducing the banding effect that could occur on the background.
  89824. */
  89825. _this.enableNoise = false;
  89826. _this._fovMultiplier = 1.0;
  89827. /**
  89828. * Enable the FOV adjustment feature controlled by fovMultiplier.
  89829. * @type {boolean}
  89830. */
  89831. _this.useEquirectangularFOV = false;
  89832. _this._maxSimultaneousLights = 4;
  89833. /**
  89834. * Number of Simultaneous lights allowed on the material.
  89835. */
  89836. _this.maxSimultaneousLights = 4;
  89837. /**
  89838. * Keep track of the image processing observer to allow dispose and replace.
  89839. */
  89840. _this._imageProcessingObserver = null;
  89841. /**
  89842. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  89843. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  89844. */
  89845. _this.switchToBGR = false;
  89846. // Temp values kept as cache in the material.
  89847. _this._renderTargets = new BABYLON.SmartArray(16);
  89848. _this._reflectionControls = BABYLON.Vector4.Zero();
  89849. // Setup the default processing configuration to the scene.
  89850. _this._attachImageProcessingConfiguration(null);
  89851. _this.getRenderTargetTextures = function () {
  89852. _this._renderTargets.reset();
  89853. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  89854. _this._renderTargets.push(_this._diffuseTexture);
  89855. }
  89856. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  89857. _this._renderTargets.push(_this._reflectionTexture);
  89858. }
  89859. return _this._renderTargets;
  89860. };
  89861. return _this;
  89862. }
  89863. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  89864. /**
  89865. * Sets the reflection reflectance fresnel values according to the default standard
  89866. * empirically know to work well :-)
  89867. */
  89868. set: function (value) {
  89869. var reflectionWeight = value;
  89870. if (reflectionWeight < 0.5) {
  89871. reflectionWeight = reflectionWeight * 2.0;
  89872. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  89873. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  89874. }
  89875. else {
  89876. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  89877. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  89878. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  89879. }
  89880. },
  89881. enumerable: true,
  89882. configurable: true
  89883. });
  89884. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  89885. /**
  89886. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  89887. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  89888. * Recommended to be keep at 1.0 except for special cases.
  89889. */
  89890. get: function () {
  89891. return this._fovMultiplier;
  89892. },
  89893. set: function (value) {
  89894. if (isNaN(value)) {
  89895. value = 1.0;
  89896. }
  89897. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  89898. },
  89899. enumerable: true,
  89900. configurable: true
  89901. });
  89902. /**
  89903. * Attaches a new image processing configuration to the PBR Material.
  89904. * @param configuration (if null the scene configuration will be use)
  89905. */
  89906. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  89907. var _this = this;
  89908. if (configuration === this._imageProcessingConfiguration) {
  89909. return;
  89910. }
  89911. // Detaches observer.
  89912. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89913. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89914. }
  89915. // Pick the scene configuration if needed.
  89916. if (!configuration) {
  89917. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  89918. }
  89919. else {
  89920. this._imageProcessingConfiguration = configuration;
  89921. }
  89922. // Attaches observer.
  89923. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89924. _this._markAllSubMeshesAsImageProcessingDirty();
  89925. });
  89926. };
  89927. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  89928. /**
  89929. * Gets the image processing configuration used either in this material.
  89930. */
  89931. get: function () {
  89932. return this._imageProcessingConfiguration;
  89933. },
  89934. /**
  89935. * Sets the Default image processing configuration used either in the this material.
  89936. *
  89937. * If sets to null, the scene one is in use.
  89938. */
  89939. set: function (value) {
  89940. this._attachImageProcessingConfiguration(value);
  89941. // Ensure the effect will be rebuilt.
  89942. this._markAllSubMeshesAsTexturesDirty();
  89943. },
  89944. enumerable: true,
  89945. configurable: true
  89946. });
  89947. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  89948. /**
  89949. * Gets wether the color curves effect is enabled.
  89950. */
  89951. get: function () {
  89952. return this.imageProcessingConfiguration.colorCurvesEnabled;
  89953. },
  89954. /**
  89955. * Sets wether the color curves effect is enabled.
  89956. */
  89957. set: function (value) {
  89958. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89959. },
  89960. enumerable: true,
  89961. configurable: true
  89962. });
  89963. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  89964. /**
  89965. * Gets wether the color grading effect is enabled.
  89966. */
  89967. get: function () {
  89968. return this.imageProcessingConfiguration.colorGradingEnabled;
  89969. },
  89970. /**
  89971. * Gets wether the color grading effect is enabled.
  89972. */
  89973. set: function (value) {
  89974. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89975. },
  89976. enumerable: true,
  89977. configurable: true
  89978. });
  89979. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  89980. /**
  89981. * Gets wether tonemapping is enabled or not.
  89982. */
  89983. get: function () {
  89984. return this._imageProcessingConfiguration.toneMappingEnabled;
  89985. },
  89986. /**
  89987. * Sets wether tonemapping is enabled or not
  89988. */
  89989. set: function (value) {
  89990. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89991. },
  89992. enumerable: true,
  89993. configurable: true
  89994. });
  89995. ;
  89996. ;
  89997. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  89998. /**
  89999. * The camera exposure used on this material.
  90000. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90001. * This corresponds to a photographic exposure.
  90002. */
  90003. get: function () {
  90004. return this._imageProcessingConfiguration.exposure;
  90005. },
  90006. /**
  90007. * The camera exposure used on this material.
  90008. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90009. * This corresponds to a photographic exposure.
  90010. */
  90011. set: function (value) {
  90012. this._imageProcessingConfiguration.exposure = value;
  90013. },
  90014. enumerable: true,
  90015. configurable: true
  90016. });
  90017. ;
  90018. ;
  90019. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  90020. /**
  90021. * Gets The camera contrast used on this material.
  90022. */
  90023. get: function () {
  90024. return this._imageProcessingConfiguration.contrast;
  90025. },
  90026. /**
  90027. * Sets The camera contrast used on this material.
  90028. */
  90029. set: function (value) {
  90030. this._imageProcessingConfiguration.contrast = value;
  90031. },
  90032. enumerable: true,
  90033. configurable: true
  90034. });
  90035. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  90036. /**
  90037. * Gets the Color Grading 2D Lookup Texture.
  90038. */
  90039. get: function () {
  90040. return this._imageProcessingConfiguration.colorGradingTexture;
  90041. },
  90042. /**
  90043. * Sets the Color Grading 2D Lookup Texture.
  90044. */
  90045. set: function (value) {
  90046. this.imageProcessingConfiguration.colorGradingTexture = value;
  90047. },
  90048. enumerable: true,
  90049. configurable: true
  90050. });
  90051. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  90052. /**
  90053. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90054. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90055. * 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;
  90056. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90057. */
  90058. get: function () {
  90059. return this.imageProcessingConfiguration.colorCurves;
  90060. },
  90061. /**
  90062. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90063. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90064. * 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;
  90065. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90066. */
  90067. set: function (value) {
  90068. this.imageProcessingConfiguration.colorCurves = value;
  90069. },
  90070. enumerable: true,
  90071. configurable: true
  90072. });
  90073. /**
  90074. * The entire material has been created in order to prevent overdraw.
  90075. * @returns false
  90076. */
  90077. BackgroundMaterial.prototype.needAlphaTesting = function () {
  90078. return true;
  90079. };
  90080. /**
  90081. * The entire material has been created in order to prevent overdraw.
  90082. * @returns true if blending is enable
  90083. */
  90084. BackgroundMaterial.prototype.needAlphaBlending = function () {
  90085. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  90086. };
  90087. /**
  90088. * Checks wether the material is ready to be rendered for a given mesh.
  90089. * @param mesh The mesh to render
  90090. * @param subMesh The submesh to check against
  90091. * @param useInstances Specify wether or not the material is used with instances
  90092. * @returns true if all the dependencies are ready (Textures, Effects...)
  90093. */
  90094. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  90095. var _this = this;
  90096. if (useInstances === void 0) { useInstances = false; }
  90097. if (subMesh.effect && this.isFrozen) {
  90098. if (this._wasPreviouslyReady) {
  90099. return true;
  90100. }
  90101. }
  90102. if (!subMesh._materialDefines) {
  90103. subMesh._materialDefines = new BackgroundMaterialDefines();
  90104. }
  90105. var scene = this.getScene();
  90106. var defines = subMesh._materialDefines;
  90107. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  90108. if (defines._renderId === scene.getRenderId()) {
  90109. return true;
  90110. }
  90111. }
  90112. var engine = scene.getEngine();
  90113. // Lights
  90114. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  90115. defines._needNormals = true;
  90116. // Textures
  90117. if (defines._areTexturesDirty) {
  90118. defines._needUVs = false;
  90119. if (scene.texturesEnabled) {
  90120. if (scene.getEngine().getCaps().textureLOD) {
  90121. defines.TEXTURELODSUPPORT = true;
  90122. }
  90123. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90124. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  90125. return false;
  90126. }
  90127. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  90128. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  90129. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  90130. defines.OPACITYFRESNEL = this._opacityFresnel;
  90131. }
  90132. else {
  90133. defines.DIFFUSE = false;
  90134. defines.DIFFUSEHASALPHA = false;
  90135. defines.GAMMADIFFUSE = false;
  90136. defines.OPACITYFRESNEL = false;
  90137. }
  90138. var reflectionTexture = this._reflectionTexture;
  90139. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90140. if (!reflectionTexture.isReadyOrNotBlocking()) {
  90141. return false;
  90142. }
  90143. defines.REFLECTION = true;
  90144. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  90145. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  90146. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  90147. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  90148. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  90149. defines.REFLECTIONBGR = this.switchToBGR;
  90150. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  90151. defines.INVERTCUBICMAP = true;
  90152. }
  90153. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  90154. switch (reflectionTexture.coordinatesMode) {
  90155. case BABYLON.Texture.CUBIC_MODE:
  90156. case BABYLON.Texture.INVCUBIC_MODE:
  90157. defines.REFLECTIONMAP_CUBIC = true;
  90158. break;
  90159. case BABYLON.Texture.EXPLICIT_MODE:
  90160. defines.REFLECTIONMAP_EXPLICIT = true;
  90161. break;
  90162. case BABYLON.Texture.PLANAR_MODE:
  90163. defines.REFLECTIONMAP_PLANAR = true;
  90164. break;
  90165. case BABYLON.Texture.PROJECTION_MODE:
  90166. defines.REFLECTIONMAP_PROJECTION = true;
  90167. break;
  90168. case BABYLON.Texture.SKYBOX_MODE:
  90169. defines.REFLECTIONMAP_SKYBOX = true;
  90170. break;
  90171. case BABYLON.Texture.SPHERICAL_MODE:
  90172. defines.REFLECTIONMAP_SPHERICAL = true;
  90173. break;
  90174. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  90175. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  90176. break;
  90177. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  90178. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  90179. break;
  90180. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  90181. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  90182. break;
  90183. }
  90184. if (this.reflectionFresnel) {
  90185. defines.REFLECTIONFRESNEL = true;
  90186. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  90187. this._reflectionControls.x = this.reflectionAmount;
  90188. this._reflectionControls.y = this.reflectionReflectance0;
  90189. this._reflectionControls.z = this.reflectionReflectance90;
  90190. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  90191. }
  90192. else {
  90193. defines.REFLECTIONFRESNEL = false;
  90194. defines.REFLECTIONFALLOFF = false;
  90195. }
  90196. }
  90197. else {
  90198. defines.REFLECTION = false;
  90199. defines.REFLECTIONFALLOFF = false;
  90200. defines.REFLECTIONBLUR = false;
  90201. defines.REFLECTIONMAP_3D = false;
  90202. defines.REFLECTIONMAP_SPHERICAL = false;
  90203. defines.REFLECTIONMAP_PLANAR = false;
  90204. defines.REFLECTIONMAP_CUBIC = false;
  90205. defines.REFLECTIONMAP_PROJECTION = false;
  90206. defines.REFLECTIONMAP_SKYBOX = false;
  90207. defines.REFLECTIONMAP_EXPLICIT = false;
  90208. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90209. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90210. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90211. defines.INVERTCUBICMAP = false;
  90212. defines.REFLECTIONMAP_OPPOSITEZ = false;
  90213. defines.LODINREFLECTIONALPHA = false;
  90214. defines.GAMMAREFLECTION = false;
  90215. }
  90216. }
  90217. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  90218. defines.USERGBCOLOR = this._useRGBColor;
  90219. defines.NOISE = this._enableNoise;
  90220. }
  90221. if (defines._areImageProcessingDirty) {
  90222. if (!this._imageProcessingConfiguration.isReady()) {
  90223. return false;
  90224. }
  90225. this._imageProcessingConfiguration.prepareDefines(defines);
  90226. }
  90227. // Misc.
  90228. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  90229. // Values that need to be evaluated on every frame
  90230. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  90231. // Attribs
  90232. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  90233. if (mesh) {
  90234. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90235. mesh.createNormals(true);
  90236. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  90237. }
  90238. }
  90239. }
  90240. // Get correct effect
  90241. if (defines.isDirty) {
  90242. defines.markAsProcessed();
  90243. scene.resetCachedMaterial();
  90244. // Fallbacks
  90245. var fallbacks = new BABYLON.EffectFallbacks();
  90246. if (defines.FOG) {
  90247. fallbacks.addFallback(0, "FOG");
  90248. }
  90249. if (defines.POINTSIZE) {
  90250. fallbacks.addFallback(1, "POINTSIZE");
  90251. }
  90252. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  90253. if (defines.NUM_BONE_INFLUENCERS > 0) {
  90254. fallbacks.addCPUSkinningFallback(0, mesh);
  90255. }
  90256. //Attributes
  90257. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90258. if (defines.NORMAL) {
  90259. attribs.push(BABYLON.VertexBuffer.NormalKind);
  90260. }
  90261. if (defines.UV1) {
  90262. attribs.push(BABYLON.VertexBuffer.UVKind);
  90263. }
  90264. if (defines.UV2) {
  90265. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90266. }
  90267. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  90268. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  90269. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  90270. "vFogInfos", "vFogColor", "pointSize",
  90271. "vClipPlane", "mBones",
  90272. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  90273. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  90274. "shadowLevel", "alpha",
  90275. "vBackgroundCenter", "vReflectionControl",
  90276. "vDiffuseInfos", "diffuseMatrix",
  90277. ];
  90278. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  90279. var uniformBuffers = ["Material", "Scene"];
  90280. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  90281. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  90282. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  90283. uniformsNames: uniforms,
  90284. uniformBuffersNames: uniformBuffers,
  90285. samplers: samplers,
  90286. defines: defines,
  90287. maxSimultaneousLights: this._maxSimultaneousLights
  90288. });
  90289. var onCompiled = function (effect) {
  90290. if (_this.onCompiled) {
  90291. _this.onCompiled(effect);
  90292. }
  90293. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  90294. };
  90295. var join = defines.toString();
  90296. subMesh.setEffect(scene.getEngine().createEffect("background", {
  90297. attributes: attribs,
  90298. uniformsNames: uniforms,
  90299. uniformBuffersNames: uniformBuffers,
  90300. samplers: samplers,
  90301. defines: join,
  90302. fallbacks: fallbacks,
  90303. onCompiled: onCompiled,
  90304. onError: this.onError,
  90305. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  90306. }, engine), defines);
  90307. this.buildUniformLayout();
  90308. }
  90309. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90310. return false;
  90311. }
  90312. defines._renderId = scene.getRenderId();
  90313. this._wasPreviouslyReady = true;
  90314. return true;
  90315. };
  90316. /**
  90317. * Build the uniform buffer used in the material.
  90318. */
  90319. BackgroundMaterial.prototype.buildUniformLayout = function () {
  90320. // Order is important !
  90321. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  90322. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  90323. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  90324. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  90325. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  90326. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  90327. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  90328. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  90329. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  90330. this._uniformBuffer.addUniform("pointSize", 1);
  90331. this._uniformBuffer.addUniform("shadowLevel", 1);
  90332. this._uniformBuffer.addUniform("alpha", 1);
  90333. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  90334. this._uniformBuffer.addUniform("vReflectionControl", 4);
  90335. this._uniformBuffer.create();
  90336. };
  90337. /**
  90338. * Unbind the material.
  90339. */
  90340. BackgroundMaterial.prototype.unbind = function () {
  90341. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  90342. this._uniformBuffer.setTexture("diffuseSampler", null);
  90343. }
  90344. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  90345. this._uniformBuffer.setTexture("reflectionSampler", null);
  90346. }
  90347. _super.prototype.unbind.call(this);
  90348. };
  90349. /**
  90350. * Bind only the world matrix to the material.
  90351. * @param world The world matrix to bind.
  90352. */
  90353. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  90354. this._activeEffect.setMatrix("world", world);
  90355. };
  90356. /**
  90357. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  90358. * @param world The world matrix to bind.
  90359. * @param subMesh The submesh to bind for.
  90360. */
  90361. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  90362. var scene = this.getScene();
  90363. var defines = subMesh._materialDefines;
  90364. if (!defines) {
  90365. return;
  90366. }
  90367. var effect = subMesh.effect;
  90368. if (!effect) {
  90369. return;
  90370. }
  90371. this._activeEffect = effect;
  90372. // Matrices
  90373. this.bindOnlyWorldMatrix(world);
  90374. // Bones
  90375. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  90376. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  90377. if (mustRebind) {
  90378. this._uniformBuffer.bindToEffect(effect, "Material");
  90379. this.bindViewProjection(effect);
  90380. var reflectionTexture = this._reflectionTexture;
  90381. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  90382. // Texture uniforms
  90383. if (scene.texturesEnabled) {
  90384. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90385. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  90386. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  90387. }
  90388. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90389. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  90390. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  90391. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  90392. }
  90393. }
  90394. if (this.shadowLevel > 0) {
  90395. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  90396. }
  90397. this._uniformBuffer.updateFloat("alpha", this.alpha);
  90398. // Point size
  90399. if (this.pointsCloud) {
  90400. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  90401. }
  90402. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  90403. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  90404. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  90405. }
  90406. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  90407. // Textures
  90408. if (scene.texturesEnabled) {
  90409. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90410. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  90411. }
  90412. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90413. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  90414. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90415. }
  90416. else if (!defines.REFLECTIONBLUR) {
  90417. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90418. }
  90419. else {
  90420. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  90421. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  90422. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  90423. }
  90424. if (defines.REFLECTIONFRESNEL) {
  90425. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  90426. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  90427. }
  90428. }
  90429. }
  90430. // Clip plane
  90431. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  90432. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  90433. }
  90434. if (mustRebind || !this.isFrozen) {
  90435. if (scene.lightsEnabled) {
  90436. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  90437. }
  90438. // View
  90439. this.bindView(effect);
  90440. // Fog
  90441. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90442. // image processing
  90443. this._imageProcessingConfiguration.bind(this._activeEffect);
  90444. }
  90445. this._uniformBuffer.update();
  90446. this._afterBind(mesh);
  90447. };
  90448. /**
  90449. * Dispose the material.
  90450. * @param forceDisposeEffect Force disposal of the associated effect.
  90451. * @param forceDisposeTextures Force disposal of the associated textures.
  90452. */
  90453. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  90454. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  90455. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  90456. if (forceDisposeTextures) {
  90457. if (this.diffuseTexture) {
  90458. this.diffuseTexture.dispose();
  90459. }
  90460. if (this.reflectionTexture) {
  90461. this.reflectionTexture.dispose();
  90462. }
  90463. }
  90464. this._renderTargets.dispose();
  90465. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90466. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90467. }
  90468. _super.prototype.dispose.call(this, forceDisposeEffect);
  90469. };
  90470. /**
  90471. * Clones the material.
  90472. * @param name The cloned name.
  90473. * @returns The cloned material.
  90474. */
  90475. BackgroundMaterial.prototype.clone = function (name) {
  90476. var _this = this;
  90477. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  90478. };
  90479. /**
  90480. * Serializes the current material to its JSON representation.
  90481. * @returns The JSON representation.
  90482. */
  90483. BackgroundMaterial.prototype.serialize = function () {
  90484. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90485. serializationObject.customType = "BABYLON.BackgroundMaterial";
  90486. return serializationObject;
  90487. };
  90488. /**
  90489. * Gets the class name of the material
  90490. * @returns "BackgroundMaterial"
  90491. */
  90492. BackgroundMaterial.prototype.getClassName = function () {
  90493. return "BackgroundMaterial";
  90494. };
  90495. /**
  90496. * Parse a JSON input to create back a background material.
  90497. * @param source The JSON data to parse
  90498. * @param scene The scene to create the parsed material in
  90499. * @param rootUrl The root url of the assets the material depends upon
  90500. * @returns the instantiated BackgroundMaterial.
  90501. */
  90502. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  90503. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  90504. };
  90505. /**
  90506. * Standard reflectance value at parallel view angle.
  90507. */
  90508. BackgroundMaterial.StandardReflectance0 = 0.05;
  90509. /**
  90510. * Standard reflectance value at grazing angle.
  90511. */
  90512. BackgroundMaterial.StandardReflectance90 = 0.5;
  90513. __decorate([
  90514. BABYLON.serializeAsColor3()
  90515. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  90516. __decorate([
  90517. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90518. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  90519. __decorate([
  90520. BABYLON.serialize()
  90521. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  90522. __decorate([
  90523. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90524. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  90525. __decorate([
  90526. BABYLON.serializeAsColor3()
  90527. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  90528. __decorate([
  90529. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90530. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  90531. __decorate([
  90532. BABYLON.serialize()
  90533. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  90534. __decorate([
  90535. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90536. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  90537. __decorate([
  90538. BABYLON.serializeAsColor3()
  90539. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  90540. __decorate([
  90541. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90542. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  90543. __decorate([
  90544. BABYLON.serialize()
  90545. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  90546. __decorate([
  90547. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90548. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  90549. __decorate([
  90550. BABYLON.serializeAsTexture()
  90551. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  90552. __decorate([
  90553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90554. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  90555. __decorate([
  90556. BABYLON.serialize()
  90557. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  90558. __decorate([
  90559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90560. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  90561. __decorate([
  90562. BABYLON.serializeAsTexture()
  90563. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  90564. __decorate([
  90565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90566. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  90567. __decorate([
  90568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90569. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  90570. __decorate([
  90571. BABYLON.serialize()
  90572. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  90573. __decorate([
  90574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90575. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  90576. __decorate([
  90577. BABYLON.serialize()
  90578. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  90579. __decorate([
  90580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90581. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  90582. __decorate([
  90583. BABYLON.serializeAsVector3()
  90584. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  90585. __decorate([
  90586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90587. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  90588. __decorate([
  90589. BABYLON.serialize()
  90590. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  90591. __decorate([
  90592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90593. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  90594. __decorate([
  90595. BABYLON.serialize()
  90596. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  90597. __decorate([
  90598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90599. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  90600. __decorate([
  90601. BABYLON.serialize()
  90602. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  90603. __decorate([
  90604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90605. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  90606. __decorate([
  90607. BABYLON.serialize()
  90608. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  90609. __decorate([
  90610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90611. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  90612. __decorate([
  90613. BABYLON.serialize()
  90614. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  90615. __decorate([
  90616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90617. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  90618. __decorate([
  90619. BABYLON.serialize()
  90620. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  90621. __decorate([
  90622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90623. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  90624. __decorate([
  90625. BABYLON.serialize()
  90626. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  90627. __decorate([
  90628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90629. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  90630. __decorate([
  90631. BABYLON.serialize()
  90632. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  90633. __decorate([
  90634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90635. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  90636. __decorate([
  90637. BABYLON.serialize()
  90638. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  90639. __decorate([
  90640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90641. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  90642. __decorate([
  90643. BABYLON.serializeAsImageProcessingConfiguration()
  90644. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  90645. return BackgroundMaterial;
  90646. }(BABYLON.PushMaterial));
  90647. BABYLON.BackgroundMaterial = BackgroundMaterial;
  90648. })(BABYLON || (BABYLON = {}));
  90649. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  90650. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90651. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90652. s = arguments[i];
  90653. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90654. t[p] = s[p];
  90655. }
  90656. return t;
  90657. };
  90658. var BABYLON;
  90659. (function (BABYLON) {
  90660. /**
  90661. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  90662. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  90663. * It also helps with the default setup of your imageProcessing configuration.
  90664. */
  90665. var EnvironmentHelper = /** @class */ (function () {
  90666. /**
  90667. * constructor
  90668. * @param options
  90669. * @param scene The scene to add the material to
  90670. */
  90671. function EnvironmentHelper(options, scene) {
  90672. var _this = this;
  90673. this._errorHandler = function (message, exception) {
  90674. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  90675. };
  90676. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  90677. this._scene = scene;
  90678. this.onErrorObservable = new BABYLON.Observable();
  90679. this._setupBackground();
  90680. this._setupImageProcessing();
  90681. }
  90682. /**
  90683. * Creates the default options for the helper.
  90684. */
  90685. EnvironmentHelper._getDefaultOptions = function () {
  90686. return {
  90687. createGround: true,
  90688. groundSize: 15,
  90689. groundTexture: this._groundTextureCDNUrl,
  90690. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90691. groundOpacity: 0.9,
  90692. enableGroundShadow: true,
  90693. groundShadowLevel: 0.5,
  90694. enableGroundMirror: false,
  90695. groundMirrorSizeRatio: 0.3,
  90696. groundMirrorBlurKernel: 64,
  90697. groundMirrorAmount: 1,
  90698. groundMirrorFresnelWeight: 1,
  90699. groundMirrorFallOffDistance: 0,
  90700. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  90701. groundYBias: 0.00001,
  90702. createSkybox: true,
  90703. skyboxSize: 20,
  90704. skyboxTexture: this._skyboxTextureCDNUrl,
  90705. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90706. backgroundYRotation: 0,
  90707. sizeAuto: true,
  90708. rootPosition: BABYLON.Vector3.Zero(),
  90709. setupImageProcessing: true,
  90710. environmentTexture: this._environmentTextureCDNUrl,
  90711. cameraExposure: 0.8,
  90712. cameraContrast: 1.2,
  90713. toneMappingEnabled: true,
  90714. };
  90715. };
  90716. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  90717. /**
  90718. * Gets the root mesh created by the helper.
  90719. */
  90720. get: function () {
  90721. return this._rootMesh;
  90722. },
  90723. enumerable: true,
  90724. configurable: true
  90725. });
  90726. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  90727. /**
  90728. * Gets the skybox created by the helper.
  90729. */
  90730. get: function () {
  90731. return this._skybox;
  90732. },
  90733. enumerable: true,
  90734. configurable: true
  90735. });
  90736. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  90737. /**
  90738. * Gets the skybox texture created by the helper.
  90739. */
  90740. get: function () {
  90741. return this._skyboxTexture;
  90742. },
  90743. enumerable: true,
  90744. configurable: true
  90745. });
  90746. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  90747. /**
  90748. * Gets the skybox material created by the helper.
  90749. */
  90750. get: function () {
  90751. return this._skyboxMaterial;
  90752. },
  90753. enumerable: true,
  90754. configurable: true
  90755. });
  90756. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  90757. /**
  90758. * Gets the ground mesh created by the helper.
  90759. */
  90760. get: function () {
  90761. return this._ground;
  90762. },
  90763. enumerable: true,
  90764. configurable: true
  90765. });
  90766. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  90767. /**
  90768. * Gets the ground texture created by the helper.
  90769. */
  90770. get: function () {
  90771. return this._groundTexture;
  90772. },
  90773. enumerable: true,
  90774. configurable: true
  90775. });
  90776. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  90777. /**
  90778. * Gets the ground mirror created by the helper.
  90779. */
  90780. get: function () {
  90781. return this._groundMirror;
  90782. },
  90783. enumerable: true,
  90784. configurable: true
  90785. });
  90786. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  90787. /**
  90788. * Gets the ground mirror render list to helps pushing the meshes
  90789. * you wish in the ground reflection.
  90790. */
  90791. get: function () {
  90792. if (this._groundMirror) {
  90793. return this._groundMirror.renderList;
  90794. }
  90795. return null;
  90796. },
  90797. enumerable: true,
  90798. configurable: true
  90799. });
  90800. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  90801. /**
  90802. * Gets the ground material created by the helper.
  90803. */
  90804. get: function () {
  90805. return this._groundMaterial;
  90806. },
  90807. enumerable: true,
  90808. configurable: true
  90809. });
  90810. /**
  90811. * Updates the background according to the new options
  90812. * @param options
  90813. */
  90814. EnvironmentHelper.prototype.updateOptions = function (options) {
  90815. var newOptions = __assign({}, this._options, options);
  90816. if (this._ground && !newOptions.createGround) {
  90817. this._ground.dispose();
  90818. this._ground = null;
  90819. }
  90820. if (this._groundMaterial && !newOptions.createGround) {
  90821. this._groundMaterial.dispose();
  90822. this._groundMaterial = null;
  90823. }
  90824. if (this._groundTexture) {
  90825. if (this._options.groundTexture != newOptions.groundTexture) {
  90826. this._groundTexture.dispose();
  90827. this._groundTexture = null;
  90828. }
  90829. }
  90830. if (this._skybox && !newOptions.createSkybox) {
  90831. this._skybox.dispose();
  90832. this._skybox = null;
  90833. }
  90834. if (this._skyboxMaterial && !newOptions.createSkybox) {
  90835. this._skyboxMaterial.dispose();
  90836. this._skyboxMaterial = null;
  90837. }
  90838. if (this._skyboxTexture) {
  90839. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  90840. this._skyboxTexture.dispose();
  90841. this._skyboxTexture = null;
  90842. }
  90843. }
  90844. if (this._groundMirror && !newOptions.enableGroundMirror) {
  90845. this._groundMirror.dispose();
  90846. this._groundMirror = null;
  90847. }
  90848. if (this._scene.environmentTexture) {
  90849. if (this._options.environmentTexture != newOptions.environmentTexture) {
  90850. this._scene.environmentTexture.dispose();
  90851. }
  90852. }
  90853. this._options = newOptions;
  90854. this._setupBackground();
  90855. this._setupImageProcessing();
  90856. };
  90857. /**
  90858. * Sets the primary color of all the available elements.
  90859. * @param color
  90860. */
  90861. EnvironmentHelper.prototype.setMainColor = function (color) {
  90862. if (this.groundMaterial) {
  90863. this.groundMaterial.primaryColor = color;
  90864. }
  90865. if (this.skyboxMaterial) {
  90866. this.skyboxMaterial.primaryColor = color;
  90867. }
  90868. if (this.groundMirror) {
  90869. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  90870. }
  90871. };
  90872. /**
  90873. * Setup the image processing according to the specified options.
  90874. */
  90875. EnvironmentHelper.prototype._setupImageProcessing = function () {
  90876. if (this._options.setupImageProcessing) {
  90877. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  90878. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  90879. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  90880. this._setupEnvironmentTexture();
  90881. }
  90882. };
  90883. /**
  90884. * Setup the environment texture according to the specified options.
  90885. */
  90886. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  90887. if (this._scene.environmentTexture) {
  90888. return;
  90889. }
  90890. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  90891. this._scene.environmentTexture = this._options.environmentTexture;
  90892. return;
  90893. }
  90894. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  90895. this._scene.environmentTexture = environmentTexture;
  90896. };
  90897. /**
  90898. * Setup the background according to the specified options.
  90899. */
  90900. EnvironmentHelper.prototype._setupBackground = function () {
  90901. if (!this._rootMesh) {
  90902. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  90903. }
  90904. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  90905. var sceneSize = this._getSceneSize();
  90906. if (this._options.createGround) {
  90907. this._setupGround(sceneSize);
  90908. this._setupGroundMaterial();
  90909. this._setupGroundDiffuseTexture();
  90910. if (this._options.enableGroundMirror) {
  90911. this._setupGroundMirrorTexture(sceneSize);
  90912. }
  90913. this._setupMirrorInGroundMaterial();
  90914. }
  90915. if (this._options.createSkybox) {
  90916. this._setupSkybox(sceneSize);
  90917. this._setupSkyboxMaterial();
  90918. this._setupSkyboxReflectionTexture();
  90919. }
  90920. this._rootMesh.position.x = sceneSize.rootPosition.x;
  90921. this._rootMesh.position.z = sceneSize.rootPosition.z;
  90922. this._rootMesh.position.y = sceneSize.rootPosition.y;
  90923. };
  90924. /**
  90925. * Get the scene sizes according to the setup.
  90926. */
  90927. EnvironmentHelper.prototype._getSceneSize = function () {
  90928. var _this = this;
  90929. var groundSize = this._options.groundSize;
  90930. var skyboxSize = this._options.skyboxSize;
  90931. var rootPosition = this._options.rootPosition;
  90932. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  90933. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90934. }
  90935. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  90936. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  90937. });
  90938. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  90939. if (this._options.sizeAuto) {
  90940. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  90941. this._scene.activeCamera.upperRadiusLimit) {
  90942. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  90943. skyboxSize = groundSize;
  90944. }
  90945. var sceneDiagonalLenght = sceneDiagonal.length();
  90946. if (sceneDiagonalLenght > groundSize) {
  90947. groundSize = sceneDiagonalLenght * 2;
  90948. skyboxSize = groundSize;
  90949. }
  90950. // 10 % bigger.
  90951. groundSize *= 1.1;
  90952. skyboxSize *= 1.5;
  90953. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  90954. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  90955. }
  90956. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90957. };
  90958. /**
  90959. * Setup the ground according to the specified options.
  90960. */
  90961. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  90962. var _this = this;
  90963. if (!this._ground) {
  90964. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  90965. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  90966. this._ground.parent = this._rootMesh;
  90967. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  90968. }
  90969. this._ground.receiveShadows = this._options.enableGroundShadow;
  90970. };
  90971. /**
  90972. * Setup the ground material according to the specified options.
  90973. */
  90974. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  90975. if (!this._groundMaterial) {
  90976. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  90977. }
  90978. this._groundMaterial.alpha = this._options.groundOpacity;
  90979. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  90980. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  90981. this._groundMaterial.primaryLevel = 1;
  90982. this._groundMaterial.primaryColor = this._options.groundColor;
  90983. this._groundMaterial.secondaryLevel = 0;
  90984. this._groundMaterial.tertiaryLevel = 0;
  90985. this._groundMaterial.useRGBColor = false;
  90986. this._groundMaterial.enableNoise = true;
  90987. if (this._ground) {
  90988. this._ground.material = this._groundMaterial;
  90989. }
  90990. };
  90991. /**
  90992. * Setup the ground diffuse texture according to the specified options.
  90993. */
  90994. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  90995. if (!this._groundMaterial) {
  90996. return;
  90997. }
  90998. if (this._groundTexture) {
  90999. return;
  91000. }
  91001. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  91002. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  91003. return;
  91004. }
  91005. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91006. diffuseTexture.gammaSpace = false;
  91007. diffuseTexture.hasAlpha = true;
  91008. this._groundMaterial.diffuseTexture = diffuseTexture;
  91009. };
  91010. /**
  91011. * Setup the ground mirror texture according to the specified options.
  91012. */
  91013. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  91014. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91015. if (!this._groundMirror) {
  91016. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  91017. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  91018. this._groundMirror.anisotropicFilteringLevel = 1;
  91019. this._groundMirror.wrapU = wrapping;
  91020. this._groundMirror.wrapV = wrapping;
  91021. this._groundMirror.gammaSpace = false;
  91022. if (this._groundMirror.renderList) {
  91023. for (var i = 0; i < this._scene.meshes.length; i++) {
  91024. var mesh = this._scene.meshes[i];
  91025. if (mesh !== this._ground &&
  91026. mesh !== this._skybox &&
  91027. mesh !== this._rootMesh) {
  91028. this._groundMirror.renderList.push(mesh);
  91029. }
  91030. }
  91031. }
  91032. }
  91033. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  91034. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  91035. };
  91036. /**
  91037. * Setup the ground to receive the mirror texture.
  91038. */
  91039. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  91040. if (this._groundMaterial) {
  91041. this._groundMaterial.reflectionTexture = this._groundMirror;
  91042. this._groundMaterial.reflectionFresnel = true;
  91043. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  91044. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  91045. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  91046. }
  91047. };
  91048. /**
  91049. * Setup the skybox according to the specified options.
  91050. */
  91051. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  91052. var _this = this;
  91053. if (!this._skybox) {
  91054. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  91055. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  91056. }
  91057. this._skybox.parent = this._rootMesh;
  91058. };
  91059. /**
  91060. * Setup the skybox material according to the specified options.
  91061. */
  91062. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  91063. if (!this._skybox) {
  91064. return;
  91065. }
  91066. if (!this._skyboxMaterial) {
  91067. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  91068. }
  91069. this._skyboxMaterial.useRGBColor = false;
  91070. this._skyboxMaterial.primaryLevel = 1;
  91071. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  91072. this._skyboxMaterial.secondaryLevel = 0;
  91073. this._skyboxMaterial.tertiaryLevel = 0;
  91074. this._skyboxMaterial.enableNoise = true;
  91075. this._skybox.material = this._skyboxMaterial;
  91076. };
  91077. /**
  91078. * Setup the skybox reflection texture according to the specified options.
  91079. */
  91080. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  91081. if (!this._skyboxMaterial) {
  91082. return;
  91083. }
  91084. if (this._skyboxTexture) {
  91085. return;
  91086. }
  91087. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  91088. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91089. return;
  91090. }
  91091. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91092. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  91093. this._skyboxTexture.gammaSpace = false;
  91094. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91095. };
  91096. /**
  91097. * Dispose all the elements created by the Helper.
  91098. */
  91099. EnvironmentHelper.prototype.dispose = function () {
  91100. if (this._groundMaterial) {
  91101. this._groundMaterial.dispose(true, true);
  91102. }
  91103. if (this._skyboxMaterial) {
  91104. this._skyboxMaterial.dispose(true, true);
  91105. }
  91106. this._rootMesh.dispose(false);
  91107. };
  91108. /**
  91109. * Default ground texture URL.
  91110. */
  91111. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  91112. /**
  91113. * Default skybox texture URL.
  91114. */
  91115. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  91116. /**
  91117. * Default environment texture URL.
  91118. */
  91119. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  91120. return EnvironmentHelper;
  91121. }());
  91122. BABYLON.EnvironmentHelper = EnvironmentHelper;
  91123. })(BABYLON || (BABYLON = {}));
  91124. //# sourceMappingURL=babylon.environmentHelper.js.map
  91125. var BABYLON;
  91126. (function (BABYLON) {
  91127. /**
  91128. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  91129. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  91130. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  91131. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  91132. */
  91133. var VideoDome = /** @class */ (function (_super) {
  91134. __extends(VideoDome, _super);
  91135. /**
  91136. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  91137. * @param name Element's name, child elements will append suffixes for their own names.
  91138. * @param urlsOrVideo
  91139. * @param options An object containing optional or exposed sub element properties:
  91140. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  91141. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  91142. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  91143. * @param options **loop=true** Automatically loop video on end.
  91144. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  91145. */
  91146. function VideoDome(name, urlsOrVideo, options, scene) {
  91147. var _this = _super.call(this, name, scene) || this;
  91148. // set defaults and manage values
  91149. name = name || "videoDome";
  91150. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  91151. options.clickToPlay = Boolean(options.clickToPlay);
  91152. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  91153. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  91154. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  91155. // create
  91156. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  91157. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  91158. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  91159. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  91160. flat: false,
  91161. radius: options.size,
  91162. subdivisions: options.resolution,
  91163. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  91164. }, scene);
  91165. // configure material
  91166. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  91167. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  91168. material.reflectionTexture = _this._videoTexture;
  91169. material.useEquirectangularFOV = true;
  91170. material.fovMultiplier = 1.0;
  91171. // configure mesh
  91172. _this._mesh.material = material;
  91173. _this._mesh.parent = _this;
  91174. // optional configuration
  91175. if (options.clickToPlay) {
  91176. scene.onPointerUp = function () {
  91177. _this._videoTexture.video.play();
  91178. };
  91179. }
  91180. return _this;
  91181. }
  91182. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  91183. /**
  91184. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91185. * Also see the options.resolution property.
  91186. */
  91187. get: function () {
  91188. return this._material.fovMultiplier;
  91189. },
  91190. set: function (value) {
  91191. this._material.fovMultiplier = value;
  91192. },
  91193. enumerable: true,
  91194. configurable: true
  91195. });
  91196. /**
  91197. * Releases resources associated with this node.
  91198. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  91199. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  91200. */
  91201. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  91202. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  91203. this._videoTexture.dispose();
  91204. this._mesh.dispose();
  91205. this._material.dispose();
  91206. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  91207. };
  91208. return VideoDome;
  91209. }(BABYLON.Node));
  91210. BABYLON.VideoDome = VideoDome;
  91211. })(BABYLON || (BABYLON = {}));
  91212. //# sourceMappingURL=babylon.videoDome.js.map
  91213. 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\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=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*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\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\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\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef 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\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\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\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=size;\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#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 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);\ngl_Position=viewProjection*worldPos;\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 vec2 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.y*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 originalSampler;\nuniform sampler2D circleOfConfusionSampler;\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{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(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"};
  91214. 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};\nuniform sampler2D shadowSampler{X};\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};\nuniform sampler2D shadowSampler{X};\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 computeShadowWithPCFCube(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 computeShadowWithPCF(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#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#else\n#ifdef 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#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,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#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};"};
  91215. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  91216. globalObject["BABYLON"] = BABYLON
  91217. return BABYLON;
  91218. });